Javascript Question

How to get value from html control store as variable using JavaScript?

I have a variable in JavaScript like following :

var testVariable="<input type='radio' name='gender' value='male' checked> Male<br><input type='radio' name='gender' value='female'>Female<br>"


Now I want to get the value of radio button which has attribute
checked
.

How can we achieve this?

Answer

You can parse the string as HTML

var testVariable = "<input type='radio' name='gender' value='male' checked> Male<br><input type='radio' name='gender' value='female'>Female<br>";

var parser = new DOMParser();
var doc    = parser.parseFromString(testVariable, "text/html");
var val    = doc.querySelector('input[type="radio"][checked]').value;

console.log(val)

Comments