Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting form variables with JavaScript

I have the following form(echoed through php), which when a radio button is selected, I want that value to be passed to a javascript function, which I can then deal with.

<form id=\"form1\" name=\"form1\" method=\"\" action=\"JavaScript:alterRecord()\">
<input name=\"radiobutton\" type=\"radio\" value=\"test1\" />Test 2<p>
<input name=\"radiobutton\" type=\"radio\" value=\"test2\" />Test 2<p>
<input name=\"radiobutton\" type=\"radio\" value=\"test3\" />Test 3<p>
<input name=\"radiobutton\" type=\"radio\" value=\"test4\" />Test 4
<input type=\"submit\" name=\"Submit\" value=\"Submit\" />
</form>

And the JavaScript

function alterRecord(value) {
alert(value);
}

I can not find out how to get the javascript to obtain the form submitted value.

like image 551
Joshxtothe4 Avatar asked May 12 '26 17:05

Joshxtothe4


2 Answers

From the top of my head:

<form onSubmit="alterRecord">
  <input type="radio" id="radio1"/>
  ...
</form>

function alterRecord() {
  var radio1 = document.getElementById('radio1');
  alert(radio1.checked);
}
like image 96
Michał Tatarynowicz Avatar answered May 14 '26 07:05

Michał Tatarynowicz


Do you want the javascript to fire when a radio button is clicked? Or when the form is submitted?

As mentioned, you can use onsubmit="alterRecord(this);" Then you can use commands such as

alert(this.radio1.checked);

if you add id's to all the radio buttons as well..

And for the javascript to fire each time a radio button is clicked

<input type="radio" onclick="alterRecord(this);" ... />

Then the "this" command would allow you to access the radio button clicked.

like image 32
peirix Avatar answered May 14 '26 06:05

peirix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!