I am having a problem when trying to use each() twice.
I have a list of radio checked buttons of which each has a datasrc of a website.
Example:
<input type="radio" checked datasrc="www.john.com" id="John">John<br/>
<input type="radio" checked datasrc="www.maria.com" id="Maria">Maria<br/>
<input type="radio" datasrc="www.joe.com" id="Joe">Joe<br/>
I want to retrieve each checked radio button so I do this:
$("input:radio").each(function(){
var name = $(this).attr("id");
if($("[id="+name+"]:checked").length == 1)
{
var src = $('#' + name).attr("datasrc")
console.log(name);
console.log(src);
}
});
Now when I retrieve every checked radio button, I want to append it with id its id and for value, its datasrc. For example:
<div id="John">www.john.com</div>
<div id="Maria">www.maria.com</div>
When I tried using each again I get manage to get it printed but several times. For example john will print 4 times and maria will print 5 times (the amount of the id).
For example:
$("input:radio").each(function () {
var name = $(this).attr("id");
if ($("[id=" + name + "]:checked").length == 1) {
var src = $('#' + name).attr("datasrc")
var html = "";
for (i = 0; i < name.length; i++) {
html += "<div id='" + name + "'>" + src + "</div>"
}
$("body").append(html);
}
});
Will print:
www.john.com
www.john.com
www.john.com
www.john.com
www.maria.com
www.maria.com
www.maria.com
www.maria.com
www.maria.com
What I’m I doing wrong?
It’s because you’re nesting a for loop inside each so the results of the for loop run as many times as the each loop…You don’t need the for loop though, a simple array and and
each()will work:Edit: Made it a function so you can use it at any time.