None
None

Reputation: 229

JS and jQuery - loop through textboxes and store value

Here's the function that checks if the form is complete.

So, what I'm trying to do:

  1. If radio is not selected, throw a message.
  2. If radio is "yes", but text is not entered, throw error.
  3. If radio is "no" but text is entered, make the text empty.
  4. If all is good, add stuff into `allResponses

The form was displayed 5 times, and input was as follows:

Yes a1

No

Yes a3

No

Yes 

Now, this input should display an error since in 5th case, "yes" is selected but nothing is entered in the textbox.

However, I get this:

https://i.sstatic.net/NXMDl.png

Also, the text is not being updated as in 1st and 3rd cases.

I don't know a lot about JS, so please provide me with as explained responses as you can.

EDIT: Complete code: http://pastebin.com/scNSNM2H

Thanks

Upvotes: 0

Views: 536

Answers (1)

gilly3
gilly3

Reputation: 91707

You have this in a loop:

var exaggerationPart = document.getElementById('exaggeration').value

And then you check to make sure it has a value for each item. But you will get the same value each time.

You are creating multiple inputs with the same id, "exaggeration". This is invalid HTML. Id's must be unique. To correct this, you can increment the id the same as you are doing with other elements (such as, input[name='response"+thisJokeIndex+"']).

var exaggerationPart = document.getElementById('exaggeration' + thisJokeIndex).value
tipTD2.append("<input type='text' name='exaggeration' id='exaggeration" + tipIndex + "' size='70'>")

Working demo: jsfiddle.net/svvge/2

Edit: To clear the value of the text box, you must change the value property of the text box element. Right now you are just changing the value of a variable.

var exaggerationInput = document.getElementById('exaggeration' + thisJokeIndex).value;
var exaggerationPart = exaggerationInput.value;
exaggerationInput.value = '';

Upvotes: 2

Related Questions