jQuery: find descendants by selector and set value by index - javascript

Say I have the following structure representing inputs for soccer matches:
<form>
<div class="match">
<div class="scores">
<input type="text">
<input type="text">
</div>
</div>
<div class="match">
<div class="scores">
<input type="text">
<input type="text">
</div>
</div>
<div class="match">
<div class="scores">
<input type="text">
<input type="text">
</div>
</div>
</form>
And I want to randomly populate each input, but each pair must be different.
So this is what I tried to do:
$('form .match .scores').each(function () {
var inputs = $(this).find('input[type=text]');
// generate scores...
inputs[0].val(score1);
inputs[1].val(score2);
});
I don't know what I am missing because when trying to populate the first input the console reports the following error:
Uncaught TypeError: inputs[0].val is not a function
What am I doing wrong?

Wrap your input in a jquery selector like $(inputs[0]) or you can use input[0].value since input[0] is a dom element.
$(function(){
$('form .match .scores').each(function () {
var inputs = $(this).find('input[type=text]');
console.log(inputs);
$(inputs[0]).val(score1);
$(inputs[1]).val(score2);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="match">
<div class="scores">
<input type="text">
<input type="text">
</div>
</div>
<div class="match">
<div class="scores">
<input type="text">
<input type="text">
</div>
</div>
<div class="match">
<div class="scores">
<input type="text">
<input type="text">
</div>
</div>
</form>

I actually answered a very similar question today:
jQuery .each() function accessing other selector via indexes
When calling a jquery array object using brackets (like inputs[0]) you're getting back an HTML node element, not a jQuery object.
try using inputs.eq(0) which will return the jQuery object in position i, then you can use jQuery's val()
for more on eq, see jQuery documentation: https://api.jquery.com/eq/
Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.

Related

jQuery selector with multiple elements including an AND operator

How do I add an AND operator for different elements to this jQuery selector?
$("h1:contains('Elements') && p:contains('Black')").nextAll().find(".button[name='commit']").each(function(i, that){
$('[name=size] option').filter(function() {
return ($(this).text() == 'Small');
}).prop('selected', true);
setTimeout(function(){
$(that).click();
}, 200*i);
});
This function is triggered by a button. I want this function to check if the h1 in the div contains the text Elements and if the p alongside the h1 contains Black. I know how to do an OR operator which is just a single comma, but I'm trying to implement an AND operator.
I could also change this into an if statement, but I have no idea how to make that.
"If the 1st selector and 2nd selector returns true, find the button[name='commit'], execute the filter function and then click."
<div class="item1">
<h1>Abstract</h1>
<p>White</p>
<div id="form">
<form>
<input>
<fieldset>
<select name="size">
</select>
</fieldset>
<fieldset>
<input class="button" name="commit">
</fieldset>
</form>
</div>
</div>
<div class="item2">
<h1>Elements</h1>
<p>Black</p>
<div id="form">
<form>
<input>
<fieldset>
<select name="size">
</select>
</fieldset>
<fieldset>
<input class="button" name="commit">
</fieldset>
</form>
</div>
</div>
From your comment (which might get cleaned up):
I want this function to check if the h1 in the div contains the text Elements and if the p alongside the h1 contains Black.
Combining that with your first JavaScript block, what you're looking for is:
$("h1:contains('Elements') + p:contains('Black')").nextAll("div").find(".button[name='commit']")...
Breakdown:
$("h1:contains('Elements') + p:contains('Black')") uses an adjacent sibling combinator (+) to only match an h1 that contains Elements if it's immediately followed by a p containing Black.
.nextAll("div") finds all following sibling div elements
.find(".button[name='commit']") finds any elements within those divs that have the class button and the name commit.
Live Example (turning the relevant buttons blue after half a second; I added type="button" and value="commit" to them for the snippet):
setTimeout(function() {
$("h1:contains('Elements') + p:contains('Black')").nextAll("div").find(".button[name='commit']").css({
color: "blue",
fontWeight: "bold"
});
}, 500);
<div class="item1">
<h1>Abstract</h1>
<p>White</p>
<div id="form">
<form>
<input>
<fieldset>
<select name="size">
</select>
</fieldset>
<fieldset>
<input class="button" type="button" name="commit" value="commit">
</fieldset>
</form>
</div>
</div>
<div class="item2">
<h1>Elements</h1>
<p>Black</p>
<div id="form">
<form>
<input>
<fieldset>
<select name="size">
</select>
</fieldset>
<fieldset>
<input class="button" type="button" name="commit" value="commit">
</fieldset>
</form>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Side note: Your quoted HTML has two elements with id="form" in them. id values must be unique in a document.

Make two input with same data value?

I have two inputs(number).
How can I duplicate data from first to second and back?
For example, I'll set some value in first input and in second input I get same value and if I set same value in second input I want to get same value in first input.
I think it must be something like that
<div class="first">
<input type="text" id="email">
</div>
<div class="second">
<input type="text" id="name">
</div>
<div id="slider"></div>
<script>
$('#email').change(function(){
$(this).val($('#name').val());
});
('#name').change(function(){
$(this).val($('#email').val());
});
$('#slider').slider();
</script>
https://jsfiddle.net/Frunky/hzh9zwfo/4/
When I'm trying to put smth in slider() function I get error in console (slider function doesn't exist)
Thanks.
You almost had it...
Try this:
$('#email').keyup(function (){
$('#name').val($(this).val()); // <-- reverse your selectors here
});
$('#name').keyup(function (){
$('#email').val($(this).val()); // <-- and here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first">
<input type="text" id="email">
</div>
<div class="second">
<input type="text" id="name">
</div>
Building on #technophobia 's answer, if you want them to update live, try this:
$('#email').keyup(function(){
$('#name').val($(this).val());
});
$('#name').keyup(function(){
$('#email').val($(this).val());
});

How can I capture a html div with all encountered value of input controls in string?

I have a div like this
<div id="content">
<div>
<input type="text"/>
</div>
</div>
and some one enter a text abc in textbox and click save then need a code which return var a='<div><input type="text" value="abc"/></div></div>'
$("#content").html() not working for me.
UPDATED: Try setting the input attribute.I Have updated this for multiple input fields.
$(document).ready(function(){
$('button').on('click',function(){
$('input').each(function(){//looping each input field here
$(this).attr('value', $(this).val());//you need to set the attribute value to get in html
});
console.log($("#content").html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<div>
<input type="text"/>
<input type="text"/>
<input type="text"/>
</div>
</div>
<button >click</button>

How to add incremental number to ID when cloned

I have a form field that I am duplicating when one clicks on the "Add" button. When an ID is duplicated, I want to add an incremental number to it. My code below is appending a 0 to the end of each new ID instead of counting. So #mark-description becomes mark-description00 instead of #mark-description2. I've looked a couple other similar posts here but am unable to determine what I'm doing wrong. Any thoughts would be much appreciated.
NOTE: I'm using ids because a jQuery plugin I'm using requires them.
Javascript:
$('#add-character-button').on('click', function () {
var source = $('.mark:last'),
clone = source.clone();
var count = 0;
clone.find('.copyme').val($(this).attr('title')).attr('id', function(i, val) {
return val + count;
});
clone.insertAfter('.mark:last');
});
HTML:
<div>
<input class="checkbox" id="standard" name="mark-type" type="checkbox" value="Standard Character">
<label class="no-placeholder" for="standard-character"></label>
<div class="standard-mark-container">
<div class="mark" id="mark-details">
<div class="mark-name">
<label class="placeholder" for="mark-name"><span>text</span></label>
<input class="copyme" id="mark-name" name="mark-name" placeholder="" title="Enter your mark name" type="text">
</div>
<div class="description">
<label class="placeholder" for="mark-description"><span>text</span
</label>
<textarea class="copyme" id="mark-description" name="mark-description" placeholder="" title="Enter a description"></textarea>
</div>
<div class="remove"> <a class="remove-mark-button" href="#" id="remove-character-button"><span>Remove</span></a>
</div>
</div>
</div>
<div class="add-mark"><a class="add-mark-button" href="#" id="add-character-button"><span>+ Add</span></a></div>
</div>
You should probably not even be using id's on the items that you are cloning. And you SHOULD be using array access notation (i.e. mark-name[]) in your field names. Without this you are only going to get one of the duplicate fields with the same name posted.
Here is what I would suggest.
HTML:
<div>
<input class="checkbox" id="standard" name="mark-type" type="checkbox" value="Standard Character">
<label class="no-placeholder" for="standard-character"></label>
<div class="standard-mark-container">
<div class="mark">
<div class="mark-name">
<label class="placeholder"><span>text</span>
<input class="copyme" name="mark-name[]" placeholder="" title="Enter your mark name" type="text">
</label>
</div>
<div class="description">
<label class="placeholder"><span>text</span>
<textarea class="copyme" name="mark-description[]" placeholder="" title="Enter a description"></textarea>
</label>
</div>
<div class="remove"><a class="remove-mark-button" href="#"><span>Remove</span></a>
</div>
</div>
</div>
<div class="add-mark"><a class="add-mark-button" href="#" id="add-character-button"><span>+ Add</span></a></div>
</div>
javascript:
$('#add-character-button').on('click', function() {
// make clone
$template = $('.mark:last');
var $clone = $template.clone();
// set values to default in clone
$clone.find('.copyme').each(function() {
$(this).val($(this).attr('title'));
});
// insert into DOM
$clone.insertAfter($template);
});
$('.remove').on('click'), function() {
$(this).closest('.mark').remove();
});
This fully eliminates the need to modify id names and simplifies your code.
is this what you're looking for? i simplified the code so i wouldnt have to type all the ids and fors and stuff. http://jsfiddle.net/swm53ran/134/
$(document).ready(function() {
var count = 0;
$('.add').on('click', function() {
count++;
var clone = $('.template').clone('true').removeClass('template');
clone.find('textarea').attr('id', 'textarea' + count);
clone.find('textarea').html('Id: ' + clone.find('textarea').attr('id'));
clone.appendTo('.sections');
});
});
Add
<div class="sections">
<div class="template section">
<input type="checkbox" /><br/>
text <input type="text"/><br/>
textarea <textarea id="textarea">Id: textarea</textarea>
</div>
</div>
although, i would suggest not using id's, but if you're intent on using them, this should work for your purposes.

foreach through div

I have got some trouble about doing an loop through the following construct:
<div id="items">
<p id="test1">
<select name="1" id="1"><option>A</option><option selected>B</option></select>
<input type="text" name="to" id="to">
<input type="text" name="away" id="awy">
</p>
<p id="test2">
<select name="2" id="2"><option>A</option><option selected>B</option></select>
<input type="text" name="to" id="to">
<input type="text" name="away" id="awy">
</p>
<p id="test3">
<select name="3" id="3"><option>A</option><option selected>B</option></select>
<input type="text" name="to" id="to">
<input type="text" name="away" id="awy">
</p>
</div>
I need to run through test1, test2 and test3 and read the selected option and the values of the text-fields (select, to,away). Doing this if i got only one thing in for example test1 is no problem with query:
$('#items').children('p').each(function () {...}
But if i add the two text-fields and want to do this for each test (1-3) I have no idea...
Any idea?
Thanks!
Ids should represent unique items within a DOM. Use classes instead, like so:
<input type="text" name="to" class="to">
<input type="text" name="away" class="awy">
How about this?
$('#items').find('select option:selected, input:text').each(function(){
alert($(this).val()); //Value of each selected option and text field within the div
});
Note: First of all give the unique id for all elements.
The following code might help you.
$(ā€˜pā€™).each(function(index){
this.children().get(0).val();
//now do for second and third also
}
You dont even need to do the .children part.
Try this:
$('#items > p').each(function () {
// you can then use $(this) to reference the currently iterated p element.
// such as $(this).find('input[type="text"]:first');
// or
// $(this).find('input[type="text"]:last');
});

Categories