I have this script in my < head > :
<script>
var rad = document.getElementsByName('search_type');
alert(rad[1]);
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log(prev.value):null;
if(this !== prev) {
prev = this;
}
console.log(this.value)
alert(this.value);
};
}
</script>
and this is my form:
<form name="search_form" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr>
<td class="input">
<input type="radio" name="search_type" value="search_code" checked>1st type<br>
<input type="radio" name="search_type" value="search_title">2nd type<br>
<input type="radio" name="search_type" value="search_filter">3rd type<br>
</td>
<tr/>
</table>
</form>
but none of alerts work. I have no error in console. please help.
You are running the script before the HTML code for the radio buttons has been parsed.
Place the script below the form, or run the code in the load event: