0

Here I have form in HTML

<form>
  <input type="text" name ="tes[]" id="tes1">
  <input type ="submit" value="Periksa Hasil" name="test">
 </form>

Button in the form will use to pass the data in php. That's why I make another button to set the value of form input like this:

<button type="button" onclick="tes_ya(tes1);">Yes</button>
<button type="button" onclick="tes_no(tes1);">No</button>

So, if user click Yes, the value of form input is 1, and if user click No, the value will be 0.

I already make a javascript like this:

function tes_ya(id){
			document.getElementById(id).value= 1;
		}
function tes_no(id){
			document.getElementById(id).value= 0;
		}

But I don't know, when I try it, the value can not e set. Is there anyone can help me please? Thank you.

2 Answers 2

4

Your click handlers for the buttons have an issue:

tes_ya(tes1);

tes1 is not defined, so when document.getElementById(id) is called with it, it's essentially calling document.getElementById(undefined) (either that or the original code will get an error and utterly fail).

What you actually want is to pass the string 'tes1':

tes_ya('tes1');
Sign up to request clarification or add additional context in comments.

1 Comment

OMG, yes! I feel so stupid I forget the quote. Thank you so much.
0

It is better to avoid onclick.

Change:

<button type="button" onclick="tes_ya(tes1);">Yes</button>

to:

<button type="button" id="yes-btn">Yes</button>

Create a function that will copy the value from the text of the button:

function copyValue() {
    document.getElementById("tes1").value = this.textContent === "Yes" ? '1' : '0';
}

Then in your JavaScript attach an event handler like so:

document.getElementById("yes-btn").addEventListener("click", copyValue);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.