jQuery - closest input to current input - javascript

I have two divs with same class names with one input inside each. First one has id, second - no, I need get closest input to my input with id. I can't set an id to second input, or change class names of divs.
HTML -
<div class="picker">
<input id="myInput"/>
</div>
<div class="picker">
<input/> <-- which I need to get ->
</div>
I have tried to use something like below, but, this operation returns me the first input.
$("#myInput").closest("input")

So you need to pick parent the "picker" and then you need to pick the next "picker" and then find the input.
const inp = $("#myInput").closest('.picker').next('.picker').find('input');
inp.val('found it');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="picker">
<input id="myInput" />
</div>
<div class="picker">
<input/>
<-- which I need to get ->
</div>

Related

Show div depending on a search

I have a small problem with a script that I want to find and show different divs depending on a search. The original script is something I found and used for a contact list, and that I now want to configure to do something else.
Original code (JSFiddle)
My edited code:
$('.Fruit').hide();
$('#search').click(function() {
$('.Fruit').hide();
var txt = $('#search-criteria').val();
$('.Fruit').each(function() {
if ($(this).id.toUpperCase().indexOf(txt.toUpperCase()) != -1) {
$(this).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div class="Fruit" id="Apple">
<h3>Some text about apples</h3>
</div>
<div class="Fruit" id="Orange">
<h3>Some text about oranges</h3>
</div>
I don't know if you understand what I'm trying to achieve...? I have, in this case, two divs - Apple and Orange. By default both are hidden, but if I enter Apple for instance in the search field and push the search button, the div "Apple" will show, and if I instead search for "Orange" then obviously I want the "Orange" div to show. If I search for anything else nothing will show, as long as there's not a div with an id that matches the searchword.
So basically I'm trying to build a database of preloaded content that can be searched and shown on the fly without reloading the page.
The error is, as far as I can understand, when I try to address and compare the divs id with the searchword on row 6 in the JS. Does anyone know how to do this, and make this work? Or does anyone have another solution that can perform this task?
The issue is because jQuery objects do not have an id property. You need to use prop('id') or just this.id.
Also note that you can improve your logic by making the id attributes you match with lower case, then convert the input to lower case, then you can just use a normal selector, like this:
$('#search').click(function() {
var txt = $('#search-criteria').val();
if (txt)
$('.fruit').hide().filter('#' + txt.toLowerCase()).show();
});
.fruit {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div class="fruit" id="apple">
<h3>Some text about apples</h3>
</div>
<div class="fruit" id="orange">
<h3>Some text about oranges</h3>
</div>

js bind input name to parent index

Is it possible to bind input element name to its parent index (div) so whenever div index changes input name is changed automatically? Something like this:
<div>
<input type="text" name="parent.index"/>
</div>
I guess thats what you need:
<div onchange = "this.children[0].name=this.parentNode.indexOf(this)">
<input type="text" />
</div>

Adding input rows using jQuery clone()

Background:
I've got a set of input elements form invoice item details. I want a user to be able to add rows of input fields for each additional item.
Input Markup
<div class="input-row">
<div class="form-group">
<label for="item_name">Item:</label>
<div>
<input type="text" name="item_name[]" placeholder="Name">
</div>
<div>
<input type="text" name="item_qty[]" placeholder="Quantity">
</div>
<div>
<input type="text" name="item_price[]" placeholder="Price">
</div>
<div>
<input type="text" name="item_total[]" placeholder="Total">
</div>
</div>
</div>
And a button to add an additional item
Button Markup
<div class="col-lg-2">
<a id="add-item" href="#">Add Item</a>
</div>
Button Javascript
$('#add-item').click(function(){
$('.input-row:first').clone().appendTo('.input-row:last');
})
Problem:
When I click the add button the first time, it works fine and adds a row of input fields after the first one, however if I click it again it adds 2 rows and then click it again it adds 4 rows. I realise this may be because the cloned .input-row div is being included in the clone, but I'm trying to only copy the first div element using the :first selector. Any ideas how to resolve this?
Question
How can I ensure only one div is appended to the markup.
The best solution I've seen so far is the following jQuery Library:
http://www.andresvidal.com/labs/relcopy.html
Solution
The jQuery appendTo method adds the element into the existing div, meaning when you clone it the second time the div contains two rows of input fields and then the third time will contain 4 rows of input fields.
To overcome this use the insertAfter() method
Button Javascript
$('#add-item').click(function(){
$('.input-row:first').clone().insertAfter('.input-row:last');
})

jQuery.val() doesn't work on an <input> tag

After typing something in an input, and clicking on the button, ".val()" return an empty value, any idea why?
HTML CODE:
<div class="mainClass">
<div class="class1" >
<div class="class2">
<h3>Settings 1</h3>
<label>
<span>Text 1:</span>
<input type="text" name="text">
</label>
<label>
<span>Text 2:</span>
<input type="text" name="text2">
</label>
</div>
</div>
<div class="class3" >
<div class="class4">
<h3>Settings 2</h3>
<label>
<span>Text 1:</span>
<input type="text" name="text">
</label>
<label>
<span>Text 2:</span>
<input type="text" name="text2">
</label>
</div>
</div>
</div>
<button id="Go" class="go" >GO </button>
JAVASCRIPT CODE:
$('#Go').on('click', function() {
alert($('.class1 input').val()); //return an empty value
$('.class1 input').val("test");
alert($('.class1 input').val()); //return test
});
EDIT:
Even this doesnt work, and here i have only one input so I can't type in the wrong one:
<div class="mainClass">
<div class="class1" >
<div class="class2">
<h3>Settings 1</h3>
<label>
<span>Text 1:</span>
<input type="text" name="text">
</label>
</div>
</div>
</div>
<button id="Go" class="go" >GO </button>
EDIT 2: I found a beginning of the problem...
When I am doing that:
$('.class1 input').each(function () {
alert($(this).attr('name') + " value:" +$(this).val() );
});
I get two "alert" like this:
text value:
text value:myinputText
So two created for one in my HTML, the first one is empty and the second one work well!
Looking closely to my page, i found that all element are duplicated( <select,field, input...)
Any idea how is that possible? Am i calling two time my html file?
And all my code is in a popup( I don't know if it can help)
(I am new in Javascript and jQuery)
Thanks
There's more than one element matching '.class1 input'. You probably didn't fill the first one of the set.
From the documentation :
Get the current value of the first element in the set of matched
elements.
While val('text') fills all matching elements :
Set the value of each element in the set of matched elements
Which is why you see something in your second alert.
You'd better use a more selective selector. Usually we use an id, or a name if a form is used to send the values to a server.
$('.class1 input').val()
refers to two elements
<input type="text" name="text">
and
<input type="text" name="text2">
You have more than one element that matches.
From the jQuery docs
.val()
Get the current value of the first element in the set of
matched elements or set the value of every matched element.
You are only getting the first element of the matched set as the docs state. If you want all the values, you need to loop over the set.
Wrap your Jquery code around a Document-ready block:
$('document').ready(function(){});
like so:
$('document').ready(function(){
$('#Go').on('click', function() {
alert($('.class1 input').val()); //return an empty value
$('.class1 input').val("test");
alert($('.class1 input').val()); //return test
});
});
Even with so much help from google search and Stackoverflow, it took us 1 hour to identify this issue.
I had a similar problem Chrome repeatedly told me .val() is not a function, instead of using .val() I had to use .value That got the job done for me hope it works for you.

Cloning a div resets all selected items of the destination div

The problem I have :
I click "add"
I select 2nd option
I click "add"
Problem : my first select-list's selected option index = 0;
This should not happen, but I can't figure out why it does it anyway. Can anyone tell me what I did wrong?
<script type="text/javascript">
function add(){
var div =document.getElementById('ruletemplate').cloneNode(true);
document.getElementById('rules').innerHTML += div.innerHTML;
return false;
}
</script>
<div id="ruletemplate" style="display: none;">
<div >
<label for="rule">Rule</label>
<select name="rules[][option]">
<option>MAX PERS</option>
<option>MIN PERS</option>
</select>
<input name="rule[][amount]" type="text"/>
</div>
</div>
<form>
<div id="rules" >
</div>
<a id="addRule" href="" onclick="javascript: add(); return false;">add</a>
<input type="Submit" value="Save" />
</form>
The reason it is doing that is you are setting the innerHTML which means the entire thing is reparsed. You will need to append the element to container instead. Try this it should keep each select's position.
function add(){
var div =document.getElementById('ruletemplate').cloneNode(true);
div.style.display='block';
document.getElementById('rules').appendChild(div);
return false;
}
The option element maintains its current selected state with the selected javascript property (not to be confused with the selected attribute, which corresponds to default selected state).
This isnt cloned - so you would have to update the selection manually
Note - you cannot have duplicate ids on a single document - when you clone you element you are duplicating ids
In some browsers (Firefox, Chrome..) the DOM object is not updated (the text input with its value and the selected option with the "select" attribute), so when you call innerHTML you get the original structure without values.
You have to force the DOM update of the object, like this: http://dev-answers.blogspot.it/2007/08/firefox-does-not-reflect-input-form.html

Categories