i have multi div with same class name and each div have multi element(input,select and ...). Now i want to add event to input element. how to find the div index when input event run?
<div class="container">
<div class='item'>
<input type="text" ng-click='test()'>
<input type="text" >
<input type="text" ng-click='test()'>
</div>
<div class='item'>
<input type="text" ng-click='test()'>
<input type="text" >
<input type="text" ng-click='test()'>
</div>
<div class='item'>
<input type="text" ng-click='test()'>
<input type="text" >
<input type="text" ng-click='test()'>
</div>
</div>
Given the comments on your original post, my understanding of your desired functionality is this: when a user types into an input element, identify the div element that is the input's container, and alert() the div element's class attribute.
In order to do this, as I said in the comment on your post, you can use jQuery's parent() method, which will return an element's parent as a jQuery object, and then use jQuery's attr() method to inspect the parent's class attribute.
JSFiddle
If you are using jQuery:
$(document).on('keyup', '.container input', function() {
var $inputElement = $(this); // `this` is the event target
var $parentDiv = $inputElement.parent();
var parentClassName = $parentDiv.attr('class');
alert(parentClassName);
});
If you are not using jQuery:
var inputElements = document.querySelectorAll('.container input');
for(var i = 0; i < inputElements.length; i++) {
inputElements[i].addEventListener('onkeyup', function(evt) {
var inputElement = evt.target; // access event target using `evt.target`
var parentDiv = inputElement.parentNode; // get the event target's parent element
alert(parentDiv.className);
});
}
Related
I have buttons to increase/decrease quantity in a cart
<div class="product-quantity">
<button class="qtyminus">-</button>
<input type="text" name="quantity" value="1" class="qty form-control">
<button class="qtyplus">+</button>
</div>
my javascript unfortunately doesn't work can't figure out why.
$('.qtyplus').on('click', function(e) {
e.preventDefault();
var num = Number($(this).closest('.qty').val());
$(this).closest('.qty').val(++num);
});
jQuery closest searches ancestors, but in this case, you're looking for the sibling element. Try siblings instead of closest
By the way, modern browsers have built-in debugging tools. It's easy to set a breakpoint and step through you code to see what's happening, and to use the console window to test things.
You should use siblings() instead of closest() as closest() searches for ancestors while siblings() searches for siblings of an element.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product-quantity">
<button class="qtyminus">-</button>
<input type="text" name="quantity" value="1" class="qty form-control">
<button class="qtyplus">+</button>
</div>
<script>
$('.qtyplus').on('click', function(e) {
e.preventDefault();
var num = Number($(this).siblings('.qty').val());
$(this).siblings('.qty').val(++num);
});
$('.qtyminus').on('click', function(e) {
e.preventDefault();
var num = Number($(this).siblings('.qty').val());
$(this).siblings('.qty').val(--num);
});
</script>
Your issue is because closest() looks up the DOM, yet .qty is a sibling to the clicked buttons, so you need to use siblings() instead.
Also note that you can use a single event handler for both buttons if you put a common class on them and provide the value to add in a data attribute. You can also negate the need to repeatedly select the same element by providing a function to val() which returns the new value based on its current one. Try this:
$('.amendqty').on('click', function(e) {
e.preventDefault();
var inc = $(this).data('inc');
$(this).siblings('.qty').val(function(i, v) {
return parseInt(v, 10) + inc;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-quantity">
<button class="amendqty" data-inc="-1">-</button>
<input type="text" name="quantity" value="1" class="qty form-control">
<button class="amendqty" data-inc="1">+</button>
</div>
I have a div which I called quote_div and is the parentElement. It contains two input type="number" elements, a <label> element which I called r_lbl (variable name) and another <label> element called r_position (so that's four elements in one div).
I put an event listener on the div so that when either input type="number" element is changed I can perform a calculation.
quote_div.addEventListener("change", calculateCost);
Now I'm trying to access the r_position element on the div using the event trigger e (which is parsed to calculateCost(e) function) but i get an undefined error which is strange because I've predefined the value for r_position.
console.log("li element position: " + e.target.parentElement.r_position.value);
Is it not possible to do things this way? If so, what have I not understood?
Depending on your HTML structure, you could use NonDocumentTypeChildNode.previousElementSibling or NonDocumentTypeChildNode.nextElementSibling:
const div = document.getElementById('quote_div');
div.addEventListener('change', (e) => {
const target = e.target;
const label = target.previousElementSibling;
console.log(label.innerText);
});
<div id="quote_div">
<label class="r_lbl" for="input1">Label 1</label>
<input id="input1" type="number" />
<label class="r_position" for="input2">Label 2</label>
<input id="input2" type="number" />
</div>
Otherwise, you could use Element.querySelector() from the parent <div> using an id, class, name or any other selector:
const div = document.getElementById('quote_div');
div.addEventListener('change', (e) => {
const div = e.target.parentElement;
const label1 = div.querySelector('.r_lbl');
const label2 = div.querySelector('.r_position');
console.log(label1.innerText, label2.innerText);
});
<div id="quote_div">
<label class="r_lbl" for="input1">Label 1</label>
<input id="input1" type="number" />
<label class="r_position" for="input2">Label 2</label>
<input id="input2" type="number" />
</div>
I'd like to get the source code of a div, so example if a div contains some tags I'd like to get them as they are in html format and update it on a textfield.
JsFiddle : https://jsfiddle.net/Lindow/g1sp1ms3/2/
HTML :
<form>
<label class="tp_box_1">
<input type="radio" name="selected_layout" class="selected_layout" value="layout_1">
<div class="box_1">
<h3>box_one</h3>
<p>1</p>
</div>
</label>
<br><hr><br>
<label class="tp_box_2">
<input type="radio" name="selected_layout" class="selected_layout" value="layout_2">
<div class="box_2">
<h3>box_two</h3>
<p>2</p>
</div>
</label>
<textarea id="mytextarea"></textarea>
<input id="submit_form" type="button" value="Send">
</form>
JavaScript :
$('input[type="radio"][name="selected_layout"]').change(function() {
if(this.checked) {
// get the specific div children of $this
var selected_layout = $(this).find('.selected_layout');
// get source code of what's inside the selected_layout
/* example :
<h3>box_two</h3>
<p>2</p>
and put it in someVariable.
*/
// and put in into textarea (all this need to happens when a radio is changed with the source code of the checked div)
var someVariable = ...
$('textarea').val(someVariable);
}
});
How can I achieve this ? How can I get the source code inside a specific div ?
First, you don't want selected_layout to be equal to: $(this).find('.selected_layout') because this already points to that element. You want it to point to the next element that comes after it.
I think this is what you are looking for:
$('input[type="radio"][name="selected_layout"]').change(function() {
if(this.checked) {
// get the index within the set of radio buttons for the radio button that was clicked
var idx = $("[type=radio][class=selected_layout]").index(this);
// Get the div structure that corresponds to the same index
var test = $("[class^='box_']")[idx];
// Now, just make that the value of the textarea
$('textarea').val(test.innerHTML);
}
});
textarea { width:100%; height:75px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label class="tp_box_1">
<input type="radio" name="selected_layout" id="sl1" class="selected_layout" value="layout_1">
<div class="box_1">
<h3>box_one</h3>
<p>1</p>
</div>
</label>
<label class="tp_box_2">
<input type="radio" name="selected_layout" id="sl2" class="selected_layout" value="layout_2">
<div class="box_2">
<h3>box_two</h3>
<p>2</p>
</div>
</label>
<textarea id="mytextarea"></textarea>
<input id="submit_form" type="button" value="Send">
</form>
Create div element with:
Template inside
class or id for identifying
Set inputs' value to desired template class/id, then on input change find the template element base on input's value and extract the innerHTML of it by using jQuery's .html() method. Then put this HTML as an new value of textarea using also the.html() method on textarea element.
HTML:
<div id="template1" style="display:none;">
<h1>Hi!</h1>
</div>
<input type="radio" onchange="findTemplate(event)" value="template1" />
<textarea class="texta"></textarea>
jQuery:
var findTemplate = function(event) {
var target = $(event.target);
var templateName = target.val();
var template = $("#"+templateName);
var template = template.html();
var textarea = $(".texta");
textarea.html(template);
};
Working fiddle: https://jsfiddle.net/rsvvx6da/1/
I basically am trying to copy my selector and create a new one.. this is what im trying to achieve...
I have many inputs in divone and dont want to list out each one in my jquery, so i would like to dynamically find the object and link to the corresponding divtwo object
<div id="divOne">
<input type="textbox" id="tb1" value="TEXTHERE">
<input type="textbox" id="tb2" value="TEXTHERE">
</div>
<div id="divTwo">
<input type="textbox" id="tb3" value="TEXTHERE">
<input type="textbox" id="tb4" value="TEXTHERE">
</div>
$("#divOne:input").bind("keyup change", function(e) {
var selector = ($(this).selector()); //hoping this would return input object from DivOne
var value = ($(this).val());
var newselector = //modify divOne object to have divTwo selector
$(newselector).val() = value;
});
Then I'd like to to save divOne text into the divTwo textbox.
I want it to look like this, only using this. So lets say i change textbox value of tb1 to "textthere":
$("#divOne:input").bind("keyup change", function(e) {
var selector = $(#divOne.attr("id", tb1")); //this should be covered dynamically using $this or another jquery method
var newselector = $(#divTwo.attr("id", tb3)); //this however should be generated dynamically by selector var
$(newselector).val() = selector.val();
});
Thanks
If you want to match corresponding elements you can use index() and eq()
var $d1Inputs = $("#divOne input").on("keyup",function(e) {
var index = $d1Inputs.index(this);
$('#divTwo input').eq(index).val($(this).val());
});
From what I understand you want to copy the value of an input in first div to the corresponding input in second div.
So you must use index() to find what is the index of the input first and the use :eq in your selector to match only the corresponding input in second div.
$("#divOne input").on("keyup",function(e) {
$("#divTwo input:eq("+$(this).index()+")").val(($(this).val()));
});
check this fiddle https://jsfiddle.net/qfey8L14/3/
As you are trying to do is having changes on second inputs as changes made on first div then; you could try-
$(document).on('keyup chage','#divOne input',function(){
// will gives index of divone input while keyup or change event occurs
$index=$('#divOne input').index($(this));
// selects input from #divTwo in array from
$divtwoinputs=$('#divTwo input');
// now reflect the value on #divtwo inputs
$($divtwoinputs[$index]).val($(this).val());
});
Hope this fix your problem if not please let me know... if fixes your problem accept this as answer...
How about using the input event and the .index() method like so:
$('#divOne > :input').on('input', function() {
var index = $(this).index();
$('#divTwo > :input').eq( index ).val( this.value );
});
$('#divOne > :input').on('input', function() {
var index = $(this).index();
$('#divTwo > :input').eq( index ).val( this.value );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divOne">
<input type="textbox" id="tb1" placeholder="TEXT HERE">
<input type="textbox" id="tb2" placeholder="TEXT HERE">
<select id="sl1">
<option value="">Select</option>
<option>1</option>
<option>2</option>
</select>
</div>
<div id="divTwo">
<input type="textbox" id="tb3" placeholder="TEXT HERE">
<input type="textbox" id="tb4" placeholder="TEXT HERE">
<select id="sl2">
<option value="">Select</option>
<option>1</option>
<option>2</option>
</select>
</div>
Note:
:input
Selects all input, textarea, select and button elements.
How can I change the index of input element dynamically based on the parent and inner parent count in jQuery.
In the following code how can I change the index of form elements
<div id='parent_container0'>
<div id='parent_inner_container0'>
<label> Name </label>
<input type='text' name='name[]'/>
<div id='child_container0'>
<div id='child_inner_container0'>
<label> Email </label>
<input type='text' name='email[]'/>
<label> Phone </label>
<input type='text' name='phone[]'/>
</div>
</div>
</div>
</div>
<div id='parent_container1'>
<div id='parent_inner_container1'>
<label> Name </label>
<input type='text' name='name[]'/>
<div id='child_container1'>
<div id='child_inner_container1'>
<label> Email </label>
<input type='text' name='email[]'/>
<label> Phone </label>
<input type='text' name='phone[]'/>
</div>
</div>
</div>
</div>
I need the changed name of form element as
name[0]
email[0][0]
phone[0][0]
name[1]
email[1][0]
phone[1][0]
Based on the parent's index of those elements in jQuery.
How can I achieve this?
Any help is appreciated.
Thanks,
Note: The requirement is to use a nested form to add more form of parent and Child with each form has nested form fields I am using the following code for changing index.
$('.parent_container').each(function(i) {
var pindex = $(this).index();
var mainfrm=$(this);
var orgname="";
mainfrm.find('.parent_container_inner').each(function(j) {
$(this).find('input, select, textarea').each(function(k){
orgname = $(this).attr('name');
orgname = orgname.replace(/[[]\d]+/g,"");
$(this).attr('name', orgname+"["+pindex+"]["+j+"]["+k+"]");
});
});
});
First, you should select your parent "containers" with:
$("div[id^=parent_container]").each(function(){
console.log(this);
});
It will print your two parent_container (parent_container0 and parent_container1). Check out here how to use selector attribute with Starts With
Then you will need to find and replace all name[], email[] and phone[].
So, you should use Ends With, to find each input you need to replace the name
$("div[id^=parent_container]").each(function(){
var parentContainerId = this.id.replace('parent_container', '');
$(this).find("input[name$='[]']").each(function(){
var newName = this.name.replace('[]', '[' + parentContainerId + ']');
this.name = newName;
})
});
Here is the Fiddle
Also, concerning your question, you should definitely take a better look into JQuery Selectors