0

I'm trying to capture the values of pairs of textboxes on my page.

I am capturing them, but it's not exactly working the way I'd want it to as I am getting duplicate data.

Here's my HTML code:

    <div id="links">
        <div id="group1">
             <input type="text" name="linkTitle" value="Google">
             <input type="text" name="linkURL" value="www.google.com">
        </div>

        <div id="group2">
             <input type="text" name="linkTitle" value="Yahoo">
             <input type="text" name="linkURL" value="www.Yahoo.com">
        </div>

    </div>

    <div>
        <input id="btnSaveLinks" type="button" value="Save">
    </div>

And here is the javascript:

    $("#btnSaveLinks").on('click', function() {
       $('#links input[type=text]').each(function () {
          var title = $(this).attr("value");
          var url = $(this).attr("value");
          console.log('title: ' + title);
          console.log('url: ' + url);
       });
    });

title: Google

url: Google

title: www.google.com

url: www.google.com

title: Yahoo

url: Yahoo

title: www.yahoo.com

url: www.yahoo.com

2 Answers 2

6

You are getting duplicated data because you are iterating over every input and then storing the same value in the two variables:

var title = $(this).attr("value");
var url = $(this).attr("value"); // same thing

Your variables title and url contain the same thing.

You could iterate over your divs and then get the inputs inside them:

$('#links div').each(function() {
      var title = $(this).find('[name=linkTitle]').val();
      var url = $(this).find('[name=linkURL]').val();
      console.log('title: ' + title);
      console.log('url: ' + url);
});

Fiddle: http://jsfiddle.net/zXTEC/

Sign up to request clarification or add additional context in comments.

Comments

1

It's duplicated because you're writing the value twice for each text box with this line $(this).attr("value"); Look at your code again and you'll see that you use this same line for each box to get the value and assign it to two different variables...

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.