How to get JQuery closest input id and data-attr? - javascript

I have multiple input fields in my form that use the Add button. I have created my button with an image tag. Each image tag has the same class. Once I click on the image I want to get the id of my closest input field as well as data attribute value. Here is example of my HTML:
<div class="formItem">
<label for="status">Status:</label>
<input type="text" name="ls_status" id="ls_status" value="" data-master="STATUS" size="10" maxlength="10" readonly />
<img src="Images/add.png" alt="Click to add value" class="masterRecords" />
</div>
<div class="formItem">
<label for="age">Age:</label>
<input type="text" name="ls_age" id="ls_age" value="" data-master="AGE" size="10" maxlength="10" readonly />
<img src="Images/add.png" alt="Click to add value" class="masterRecords" />
</div>
Here is what I tried in JQuery:
$('.masterRecords').on('click', function(){
console.log($(this).closest('input').prop('id'));
});
In my debugging console I see 'undefined' only. First of all I'm not sure if I approached the best way to solve this problem. I repeat there is multiple elements that use the same class and I need to pull ID and data for each of them. They are all in separate div containers as you can see in my example above. If anyone see where is bug in my code please let me know. Also I would like to hear some suggestions if there is better way to do this with JQuery/HTML5/CSS3. Thank you.

Try using siblings instead of closest.
$('.masterRecords').on('click', function(){
console.log($(this).siblings('input').prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="formItem">
<label for="status">Status:</label>
<input type="text" name="ls_status" id="ls_status" value="" data-master="STATUS" size="10" maxlength="10" readonly />
<img src="https://i.stack.imgur.com/Qo01e.png" alt="Click to add value" class="masterRecords" />
</div>
<div class="formItem">
<label for="age">Age:</label>
<input type="text" name="ls_age" id="ls_age" value="" data-master="AGE" size="10" maxlength="10" readonly />
<img src="https://i.stack.imgur.com/Qo01e.png" alt="Click to add value" class="masterRecords" />
</div>

Solution: https://jsfiddle.net/jdjc1bc7/
$('.masterRecords').on('click', function(){
console.log($(this).siblings('input').prop('id'));
});
You can check for input in siblings, since in your current DOM the inputs are sibling to the element which is being clicked.
This should be the fastest way for you. https://jsperf.com/jquery-siblings-vs-parent-find-vs-find

If your structure will always be like this, you could also retrieve your related input with
$('input', $(this).parent())
which will return all inputs in the same div as the image

Because input is to the left of you can find it like this:
$('.masterRecords').on('click', function(){
console.log($(this).prev('input').prop('id'));
});
If input was after button then you can find it like this:
$('.masterRecords').on('click', function(){
console.log($(this).next('input').prop('id'));
});
Then for data attribute value just use .data or .attr of ID value you get:
$('#'+ID).attr('data-master');
$('.masterRecords').on('click', function(){
var inputTextId = $(this).prev('input').prop('id');
console.log(inputTextId);
console.log($('#'+inputTextId).attr('data-master'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="formItem">
<label for="status">Status:</label>
<input type="text" name="ls_status" id="ls_status" value="" data-master="STATUS" size="10" maxlength="10" readonly />
<img src="Images/add.png" alt="Click to add value" class="masterRecords" />
</div>
<div class="formItem">
<label for="age">Age:</label>
<input type="text" name="ls_age" id="ls_age" value="" data-master="AGE" size="10" maxlength="10" readonly />
<img src="Images/add.png" alt="Click to add value" class="masterRecords" />
</div>

The <INPUT/> element is not an ancestor of your image. Try:
$('.masterRecords').on('click', function(){
console.log($(this).closest(".formItem").find('input').attr('id'));
});

Related

add dynamically generated fields from form

Hi guys i want to dynamically add a group of input fields when a button is pressed. This works with 1 group, but not with more than one. Here is my HTML:
<form action="address.php" method="POST">
<div id="list">
<input type="text" name="address" placeholder="Address">
<input type="text" name="suburb" placeholder="Suburb">
<input type="text" name="state" placeholder="State">
<input type="text" name="country" placeholder="Country">
<button id="addMore">Add Address</button>
</div>
</form>
I'm calling the addMore function with this javascript:
$(function(){
$("#addMore").click(function(e){
e.preventDefault();
$("#list").append("<input type="text" name="address" placeholder="Address"><input type="text" name="suburb" placeholder="Suburb"><input type="text" name="state" placeholder="State"><input type="text" name="country" placeholder="Country"><button id="addMore2">Add Address</button></div>");
});
});
I've added a button at the end with an id of addMore2 because i wanna generate a similar set of input controls but with different names. I want to call that id with this function:
$(function(){
$("#addMore2").click(function(e){
e.preventDefault();
$("#list").append("<input type="text" name="address2" placeholder="Address"><input type="text" name="suburb2" placeholder="Suburb"><input type="text" name="state2" placeholder="State"><input type="text" name="country2" placeholder="Country"><button id="addMore3">Add Address</button></div>");
});
});
... and then another set of controls with the function addMore3. Same as above, but with the number 3.
If i use each function alone, it works. But if i try to use all 3 together, it doesn't work. How can i dynamically reproduce a set of input controls with different names?
you could do something like this
$(var count = 0;
$("#addMore2").click(function(e){
e.preventDefault();
$("#list").append("<input type='text' name='address2'"+count+" placeholder="Address"><input type="text" name='suburb2'"+count+" placeholder="Suburb"><input type="text" name='state2'"+count+" placeholder="State"><input type="text" name='country2'"+count+" placeholder="Country"><button id='addMore3'"+count+">Add Address</button></div>");
count++;
});
});
#rayzor
You need to append your code before button
Please use below code:
jQuery("#addMore").click(function(e){
jQuery('<br><input type="text" name="address" placeholder="Address"><input type="text" name="suburb" placeholder="Suburb"><input type="text" name="state" placeholder="State"><input type="text" name="country" placeholder="Country">').insertAfter("input:last");
return false;
});
And remove code for $("#addMore2").click event
There's no need to add Addmore 2,3,etc manually. the js will add it automatically, as much as your want. Feel free to see this one: https://phppot.com/jquery/jquery-ajax-inline-crud-with-php/

Show Text In A DIV On Blur Of Form Field

I have been searching this for over 5 hours now with no help lol.
I want to have a form field (text) that someone can type into. Either as they type or after the blur of the field I want that text to show in a div on the screen. Maybe this is not possible.
Here is the last piece of code I tried and of course it does not work.
<p>Headline Text:<br />
<input type="text" name="headline" value="$headline" onChange="document.getElementById('headline2').value=this.value" /></p>
<br />
<div id="headline2"></div>
In that code, anything typed into headline would appear in the <div id="headline2"></div> on blur.
Any help would be great.
You were not far!!!
A <div> doesn't have a value... But has inner HTML. ;)
Here it is on change:
<p>Headline Text:<br />
<input type="text" name="headline" value="$headline" onChange="document.getElementById('headline2').innerHTML=this.value" /></p>
<br />
<div id="headline2"></div>
And on keyup:
<p>Headline Text:<br />
<input type="text" name="headline" value="$headline" onKeyup="document.getElementById('headline2').innerHTML=this.value" /></p>
<br />
<div id="headline2"></div>
HTML:
<input>
<div id="target"></div>
Javascript:
var input = document.querySelector('input');
var target = document.querySelector('div')
input.addEventListener('blur', function() {
target.innerHTML = input.value
})
I recommend keeping your scripts separate from the markup, but if you so choose...
<input onblur="document.getElementById('target').innerHTML = this.value">
<div id="target"></div>
Form inputs have a value property, container elements such as divs have innerHTML. Try this instead:
<p>Headline Text:<br />
<input type="text" name="headline" value="$headline"
onChange="document.getElementById('headline2').innerHTML=this.value" />
</p>
<br />
<div id="headline2"></div>
<input type="text" id="text" onkeyup="getTextVal()">
<div id="showtext"></div>
<script>
function getTextVal(){
var val = document.getElementById('text').value;
var showText = document.getElementById('showtext');
showText.innerText = val;
}
</script>
See in jsfiddle link
This is very possible, and you were very close with your attempt. The problem is that a <div> element doesn't have a value, only innerHTML. Also, you're probably looking for onblur instead of onChange:
<p>Headline Text:<br />
<input type="text" name="headline" value="$headline" onblur="document.getElementById('headline2').innerHTML = this.value" /></p>
<br />
<div id="headline2"></div>
Just remember that with onblur, you have to actually click outside of the element for the changes to show. If you want it to change whenever the user types something, you're looking for onkeyup instead.
Hope this helps! :)

jQuery remove selected element, dynamically generated

I have a form and I can dynamically add more lines but if I try to remove a specific line it does not work, however the first line gets removed with no problem.
Here is the html:
<form class="order-form">
<div class="product-lines">
<!-- Product Line Section -->
<div class="product-line">
<img alt="remove" src="img/close.png" />
<input class="input-text" name="product-code" type="text" placeholder="Product Code" ></input>
<input class="input-text" name="product-quantity" type="text" placeholder="Quantity"></input>
<input class="input-text" name="product-discript" type="text" placeholder="Discription of Product"></input>
<label class="label-sign">£</label>
<input class="input-text" name="product-price" type="text" placeholder="RRP Price"></input>
<br>
</div>
</div>
<div id="product-btn">
<input name="btn-add-line" type="button" value="Add new line"></input>
<input name="btn-update" type="button" value="Update"></input>
<input name="btn-submit" type="submit" value="Submit Order"></input>
<label class="label-sign">£</label>
<input class="input-text" name="order-info" type="text" placeholder="Order total" ></input>
</div>
</form>
The jQuery code I have tried:
$(".btn-close").on("click", function(e){
$(e.currentTarget).parent().remove();
});
I've also Tried
$(e.currentTarget).parents("div.product-lines).next("div.product-line).remove();
Any help would be most appreciated, also a explanation would be very helpful for me to learn.
Try something like
$(".product-lines").on("click", ".btn-close", function(e){
$(e.currentTarget).parent().remove();
});
You cannot attach events to objects that are not currently on page (lines).
You have to attach click event on product-lines object and when it is clicked you delegate event to "closest" product-line object!
You will need to changed the jQuery slightly to allow for Event Delegation. This means all elements added in future will get the event attached to them too.
$(document).on("click", ".btn-close", function(e){
$(e.currentTarget).parent().remove();
});
$('body').on('click','button id/class',function(){
$(e.currentTarget).parent().remove();
});
but if u use this code it will remove <div class="product-line">...</div>
why you want to remove this div.
i dont get your question very well. Explain in details and step by step .

Create elements based on checkbox selection

I have this HTML:
<fieldset style="" title="Variaciones" id="product-create-step-3" class="fstep">
<legend>Variaciones</legend>
<section id="choices">
<input type="checkbox" value="24" id="24" name="Size"> Size
<input type="checkbox" value="25" id="25" name="Color"> Color
<section style="display: none" class="options_holder"></section>
<section style="display: none" class="variations_holder"></section></section>
</fieldset>
I need to create some input based on what checkbox/es was marked. For example if I mark first one 'Size' I should obtain this:
<section style="display: none" class="options_holder">
<input name="size[24][]" value="" placeholder="Write your size" />
</section>
if I mark second one 'Color' I should obtain this:
<section style="display: none" class="options_holder">
<input name="color[25][]" value="" placeholder="Write your color" />
</section>
if I mark both 'Size' & 'Color' I should obtain this:
<section style="display: none" class="options_holder">
<input name="size[24][]" value="" placeholder="Write your size" />
<input name="color[25][]" value="" placeholder="Write your color" />
</section>
How I would do that?
UPDATE 1
I'm trying to get which checkbox was checked by doing this:
$("#choices :checked").each(function() {
console.log(this.id + "was checked");
});
But it's not working
UPDATE 2
I realize into another problem, how I check when a checkbox was checked and after trigger some code without know any data of the checkbox? I have a code that generates check-boxes on the fly so I'll never know their name's or id's or any other data. My template for that creation looks like this:
<input type="checkbox" name="{{ entity.getLabel|lower }}" id="{{ entity.getLabel|lower ~ "_choice" }}" value="{{ entity.getId }}" /> {{ entity.getLabel }}
Where for example name could take "color" and in that case id will be "color_choice" or name could take "size" and in that case id will be "size_choice", sometimes one is created some time both are created. What I need to know and I don't is how to know which check-box was checked and when trigger some event as for example create some others input's on the fly. How do I deal with this part too?
So, your javascript should work if you change your selector to include the element that uses the pseudo-selector:
$("#choices input:checked").each(function() {
console.log(this.id + "was checked");
});
As for accessing the attribute values, you can use either the native javascript object that you're using, i.e.:
console.log("value is " + this.value);
Or you can use jQuery's attr()
console.log("name is " + $(this).attr('name'))
A working example showing both cases, as well as having attached the event to any click of input items is at this jsfiddle:
http://jsfiddle.net/k3B73/
<fieldset style="" title="Variaciones" id="product-create-step-3" class="fstep">
<legend>Variaciones</legend>
<section>
<input type="checkbox" value="24" id="24" name="Size" id='size_choice'> Size
<input type="checkbox" value="25" id="25" name="Color" id='color_choice'> Color
<section style="display: none" class="options_holder" id='options_holder'></section>
<section style="display: none" class="variations_holder"></section>
</section>
</fieldset>
<script type="text/javascript">
$(document).ready(function(){
$('#size_choice').click(function(){
if ($(this).is(':checked'))
$("#options_holder").append('<input name="size[24][]" value="" placeholder="Write your size" id="size" />');
else
$("#size").destroy();
});
$('#color_choice').click(function(){
if ($(this).is(':checked'))
$("#options_holder").append('<input name="color[25][]" value="" placeholder="Write your color" id="choice" />');
else
$("#color").destroy();
});
})
</script>

Jquery .show Issue on IE

I have a form, and when certain inputs are filled another div will display beneath the form. The following is the code:
<form>
<div class="fieldtitle">Full Name:* </div><input type="text" value="" name="fullname" id="fullname" />
<div class="fieldtitle">Email:* </div><input type="text" value="" name="email" id="emailfield" />
<div class="fieldtitle">Contact No:* </div><input type="text" value="" name="contact" id="contact" />
</form>
<div id="demo1" style="width:300px; display:none;"></div>
<script type="text/javascript">
$("#formarea").keyup(function(){
if($(fullname).val() && $(emailfield).val() && $(contact).val() && $(quantity).val()) {
$("#demo1").show();
if($.browser.msie){
$('#demo1').css({"visibility":"visible"});
}
} else {
$("#demo1").hide();
}
});
</script>
It is working on all browsers, except for IE - any suggestions as how to solve this?
The html is missing the quantity field, which will cause logic issues in the Javascript.
<form>
<div class="fieldtitle">Full Name:* </div><input type="text" value="" name="fullname" id="fullname" />
<div class="fieldtitle">Email:* </div><input type="text" value="" name="email" id="emailfield" />
<div class="fieldtitle">Contact No:* </div><input type="text" value="" name="contact" id="contact" />
<div class="fieldtitle">Quantity:* </div><input type="text" value="" name="quantity" id="quantity" />
</form>
<div id="demo1" style="width:300px; display:none;">Test</div>
The Javascript binds the event to the wrong element. It should bind toinputs instead of the form. Also the selectors passed in for each input should be string literals using the css id selector.
$("input").keyup(function(){
if($("#fullname").val() && $("#emailfield").val() && $("#contact").val() && $("#quantity").val()) {
$("#demo1").show();
} else {
$("#demo1").hide();
}
});
There is also no need for the IE conditional. Jquery's show()/hide() methods are cross browser compatible.
Example: http://jsfiddle.net/DEfVS/1/
IE dont like suggested id or name selector, you dont use it in the right way. Specify which selector you are targetting.
e.g:
Replace
$(fullname)
With
$('#fullname')
And so on...
By the way, cannot see in your sample code any form with ID 'formarea'.
And remove this: if($.browser.msie){...} its useless.

Categories

Resources