HTML:
<div id="block">
<input type="text" value="1" id="number" />
<div id="price"></div>
</div>
<div id="block">
<input type="text" value="1" id="number" />
<div id="price"></div>
</div>
jQuery:
<script type="text/javascript">
$(function() {
$("#number").keyup(function () {
var value = $(this).val()*5;
$("#price").text(value);
}).keyup();
});
</script>
Price is only displayed at first. Why?
How it is correct to make?
Blocks can be endless.
UPDATE:
Make:
var id = 1;
$('.number').each(function() {
$(this).attr('id', 'id_' + id++);
});
How it associate?
Blocks can be endless.
Your code is searching for id = price where as your html has price as class.
Basically instead of
$("#price").text(value);
you should be using
$(".price").text(value);
# is used for id selector and . is used for class selector
Update:
As per edited Code:
In your html there are two div with the same id, whereas every element should have a unique id. Please change id of the element to be unique may be price1, price2 and then use
jQuery('#price1').text(value) or jQuery('#price2').text(value) as per your case
I'd suggest using the following:
$('input:text.number').keyup(
function() {
var v = parseFloat($(this).val()),
s = v*5;
$(this).next('.price').text(s);
});
JS Fiddle demo.
The jQuery, onkeyup, takes the current user-entered value of the input, parses it to make sure it's a number, and then updates the next sibling-element that matches the supplied selector (.price) of the text-input, with the calculated number.
The above uses corrected, and now-valid, HTML:
<div class="block">
<input type="text" value="1" class="number" />
<div class="price"></div>
</div>
<div class="block">
<input type="text" value="1" class="number" />
<div class="price"></div>
</div>
References:
next().
parseFloat().
text().
:text selector.
val().
Related
I want to populate the value of the "eventTitle" in "Requirement" input box when some one click on the corresponding check box. i.e If some one clieck on the check box of Vels Group Of Instutions then automatically i want this to populate in texbox with name "Requirement" if multiple check box are clicked i want it to be comma seperated. Below is the code i tried to get but it is not working and getting undefined.
<div class="wid100">
<div class="eventTitle">Vels Group Of Instutions</div>
<div class="eventDate">2017-07-25</div>
<div class="eventVenue">This is world wide institute of technology </div>
<div class="selectEvent">
<input type="checkbox" class="seminar selected" id="179">
<label for="179"></label>
</div>
</div>
<div class="wid100">
<div class="eventTitle">Title goes here</div>
<div class="eventDate">2017-07-25</div>
<div class="eventVenue">sdfdsafasdfdsafdsafsadfsdfsdf </div>
<div class="selectEvent">
<input type="checkbox" class="seminar" id="179">
<label for="179"></label>
</div>
</div>
<input type="text" name="Requirement" placeholder="Title 01" id="divclass" required="required" class="pull-left" />
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
$(".seminar").click(function () {
if ($(this).is(":checked")) {
//checked
$(this).addClass("selected");
var event_title = "";
event_title = $(".selected").siblings('.eventTitle').val();
console.log(event_title); return false;
} else {
//unchecked
$(this).removeClass("selected");
}
});
.eventTitle is not the sibling of .selected and the .eventTitle is a div element having no value, text there. change this line
event_title = $(".selected").siblings('.eventTitle').val();
to
event_title = $(this).parent().siblings('.eventTitle').text();
or
event_title = $(this).parent().siblings('.eventTitle').html();
The issue you have is because .eventTitle is not a sibling of the clicked checkbox, so the DOM traversal logic is wrong. div elements also do not have a val(), so you should use text() or html() instead.
However, you can improve the logic and also achieve the comma separated list of the selected event titles by using map() to build an array which you can then join() before setting in the value of #divclass. Try this:
$(".seminar").click(function() {
$(this).toggleClass('selected', this.checked);
var eventNames = $('.seminar:checked').map(function() {
return $(this).closest('.wid100').find('.eventTitle').text();
}).get().join(',');
$('#divclass').val(eventNames);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wid100">
<div class="eventTitle">Vels Group Of Instutions</div>
<div class="eventDate">2017-07-25</div>
<div class="eventVenue">This is world wide institute of technology </div>
<div class="selectEvent">
<input type="checkbox" class="seminar selected" id="179">
<label for="179"></label>
</div>
</div>
<div class="wid100">
<div class="eventTitle">Title goes here</div>
<div class="eventDate">2017-07-25</div>
<div class="eventVenue">sdfdsafasdfdsafdsafsadfsdfsdf </div>
<div class="selectEvent">
<input type="checkbox" class="seminar" id="179">
<label for="179"></label>
</div>
</div>
<input type="text" name="Requirement" placeholder="Title 01" id="divclass" required="required" class="pull-left" size="100" />
I'd suggest changing the id of the #divclass to something more descriptive, as the element is not a div, and it's an identifier, not a class.
Finally, your .seminar elements have the same id attribute which is invalid. You should ensure that the ids are unique within the DOM - assuming that this is not just a typo from copy/pasting the code in the question.
i want to get each value when a button clicked.
what i missed?
//add row
$("#btnAdd").click(function(){
$(".oItem:last").clone().insertAfter(".oItem:last");
});
//submit
$("#btnCalc").click(function(){
$("[id^=txtItemName]").each(function(){
alert($("#txtItemName").val());
});
});
my fiddle here
https://jsfiddle.net/k5ndm840/3/
thanks
You are using the same ID for each new field being added. You should use class instead of id in your case as id has to be unique.
Use $(this).val(); as you will be getting this => current element in each iteration. In each callback, this refers to the element
$("#txtItemName") will always select first element having id as txtItemName
Try this:
$("#btnAdd").click(function() {
$(".oItem:last").clone().insertAfter(".oItem:last");
});
$("#btnCalc").click(function() {
$("[id^=txtItemName]").each(function() {
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btnAdd">Add</button>
<button id="btnCalc">Submit</button>
<div class="masterItem">
<div class="row oItem">
<div class="col-md-4">
<div class="form-group">
<div class="input-group"><span class="input-group-addon" style="font-weight:bold;color:#330099">Quantity</span>
<input id="txtItemName" type="text" class="form-control" placeholder="put random number here" aria-describedby="basic-addon1">
</div>
</div>
</div>
</div>
</div>
Fiddle here
Edit: As per the www standards, There must not be multiple elements in a document that have the same id value. [Ref]. As you are dealing with attribute selector, you are not facing any issue but ID MUST BE UNIQUE
Edit: To find another child under the parent element, use .closest() to find the parent element and .find() to select child of the parent.
Try this:
$("#btnAdd").click(function() {
$(".oItem:last").clone().insertAfter(".oItem:last");
});
$("#btnCalc").click(function() {
$("[id^=txtItemName]").each(function() {
alert($(this).val());
alert($(this).closest(".form-group").find('[id=txtTwo]').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="btnAdd">Add</button>
<button id="btnCalc">Submit</button>
<div class="masterItem">
<div class="row oItem">
<div class="col-md-4">
<div class="form-group">
<div class="input-group"><span class="input-group-addon" style="font-weight:bold;color:#330099">Quantity</span>
<input id="txtItemName" type="text" class="form-control" placeholder="put random number here" aria-describedby="basic-addon1">
<input id="txtTwo" placeholder="second input">
</div>
</div>
</div>
</div>
</div>
when you are trying to access the elements with id it will always give the first element matching the selector criteria.
$("#txtItemName").val()
This will always give the value of first matching element. Try to do like this.
//submit
$("#btnCalc").click(function(){
$("[id^=txtItemName]").each(function(){
console.log($(this).val());
});
});
I want to be able to display the same piece of html code 10 times under the div called: <div id="add_remove_product_name"> By clicking on the button called: <button id="add_another_product_name">. I think I need some kind of a for loop for the job but are not sure. Any suggestion will be helpful, thanks.
My HTML code:
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required></label>
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="add_remove_product_name">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required></label>
<button id="remove_product_name">X</button>
</div>
Use a for loop to concatenate 10 copies of the HTML code. Then use .after() to put this after the DIV.
$("#add_another_product_name").click(function() {
var html = '';
for (var i = 0; i < 10; i++) {
html += 'html code that you want to repeat';
}
$("#add_remove_product_name").after(html);
}
You can use jQuery clone() however when cloning an element all the attributes will be the same. Fo example they will all have the same id attribute which will cause problems and it is not valid html
So in order to do the clone correctly you have fix the cloned element
DEMO: http://jsfiddle.net/rpyt445e/
var $tpl = $('#product_name').clone();
var num = 0
$('#clone').click(function () {
num++;
var $cloned = $tpl.clone();
$cloned.attr('id', $tpl.attr('id') + '_' + num);
$(':not([id=""])', $cloned).each(function(){
$(this).attr('id', $(this).attr('id') + '_'+num);
});
$cloned.appendTo('#wrapper');
});
HTML:
<div id="wrapper">
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required />
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="add_remove_product_name">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required />
<button id="remove_product_name">X</button>
</div>
</div>
</div>
<button id="clone">Clone</button>
A technique for adding the additional elements without having to create ugly strings of html in the JavaScript is to start with one hidden set of the elements in the html. At page load time, you remove that set, but keep a reference to it. Then when you want to add a set to the page, you clone the set you removed. All of this is easier if you add a container div around the additional inputs.
You also need to make sure id attribute values are unique. In the case of the remove buttons, you can replace the id with a class. As for the input id values, if you really need them, you can add an index value to them.
Since the remove buttons are dynamically added, I suggest using event delegation when binding the click-handler.
HTML:
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required="required"/>
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="additional_product_names">
<div class="add_remove_product_name" style="display: none;">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required="required"/>
<button class="remove_product_name">X</button>
</div>
</div>
</div>
JavaScript:
$(function() {
var MAX = 10;
var $addBtn = $('#add_another_product_name'),
$additionalContainer = $('#additional_product_names');
$TEMPLATE = $additionalContainer.children(':first').remove();
function update() {
var $additonalDivs = $additionalContainer.children();
// Enable/disable the add button.
$addBtn.prop('disabled', $additonalDivs.length >= MAX);
// Re-index the "id" attributes.
$additonalDivs.find('input').attr('id', function(i) {
return 'added_product_name[' + i + ']';
});
}
$addBtn.click(function() {
$TEMPLATE.clone().appendTo($additionalContainer).show();
update();
});
$('#product_name').on('click', '.remove_product_name', function() {
$(this).closest('.add_remove_product_name').remove();
update();
});
});
jsfiddle
This is my first post on this site so hopefully you will go easy on me. I'm trying to create an HTML / PHP form and use a small piece of Javascript to add additional rows to a table when a button is clicked and increment the ID for the two fields.
The button works in adding the rows however it doesn't seem to increment the ID, just use the same ID as the previous row. Hopefully someone could help?
$(window).load(function(){
var table = $('#productanddates')[0];
var newIDSuffix = 2;
$(table).delegate('#button2', 'click', function () {
var thisRow = $(this).closest('tr')[0];
var cloned = $(thisRow).clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
id = id.substring(0, id.length - 1) + newIDSuffix;
$(this).attr('id', id);
});
cloned.insertAfter(thisRow).find('input:date').val('');
newIDSuffix++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blue-bar ta-l">
<div class="container">
<h1>Submit Your Insurance Renewal Date(s)</h1>
</div>
</div>
<div class="grey-bar">
<div class="container">
<div class="rounded-box">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" autocomplete="off" required />
</div>
<div>
<label for="name">Renewal Dates</label>
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="5" id="productanddates" class="border">
<tr>
<td>
<select name="insurance_type1" id="insurance_type1">
<option></option>
<option>Car</option>
<option>Home</option>
<option>Van</option>
<option>Business</option>
<option>GAP</option>
<option>Travel</option>
</select>
</td>
<td>
<input type="date" name="renewal_date1" id="renewal_date1" />
</td>
<td>
<input type="button" name="button2" id="button2" value="+" />
</td>
</tr>
</table>
<div>
<label for="telephone_number">Contact Number</label>
<input type="tel" id="telephone_number" name="telephone_number" pattern="\d{11}" autocomplete="off" required />
</div>
<div>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" autocomplete="off" required />
</div>
<div>
<input name="submit" type="submit" value="Submit" class="btn">
</div>
</div>
cloned.insertAfter(thisRow).find('input:date').val('');
This line isn't correct. It will throw an invalid selector error.
You need to change it to:
cloned.insertAfter(thisRow).find('input[type="date"]').val('');
jQuery actually does support the :INPUT-TYPE format in selectors, but not the new HTML5 input types (yet): so using input[type="date"] here is the correct way for now to select an element with an HTML5 type. Please notice the quotes around the value. If you want to select an attribute with a certain value.
A selector overview of css selectors here: W3schools.
Because this line is throwing an error your newIDSuffix never gets updated, because the script halts at the line before that because of the script error.
#Charlietfl raises a valid point about learning more about classes and DOM traversal. However that will not fix this code. Or explain why your code isn't working. Nevertheless it's a good tip.
I've gone ahead an taken a stab at a cleaner version of what I think that you are trying to accomplish. I'll walk through the major updates:
Updated the button id and name from "button2" to "button1" - I assumed that you would want to keep the indices in sync across the inputs in each row.
Changing $(window).load(function() { to $("document").ready(function() { - While either will work, the former will wait until all images have finished loading, while the latter while fire once the DOM has completed building. Unless you REALLY want the images to load first, I'd recommend $("document").ready(), for faster triggering of the code.
Removing the [0] references - the primary reason to use [0] after a jQuery selector collection is to reference the DOM version of the selected jQuery element, in order to us a "vanilla" JavaScript method on it. In all cases, you were re-rwapping the variables in $(...), which just converted the DOM element back into a jQuery object, so that extra step was not needed.
Changed the .delegate() method to .on() - as Howard Renollet noted, that is the correct method to use for modern versions of jQuery. Note that the "event" and "target" parameters have swapped places in on, from where they were in delegate.
Changed the event target from #button2 to :button - this will make sure that all of the buttons in the new rows will also allow you to add additional rows, not just the first one.
Switched the clone target from the clicked row to the last row in the table - this will help keep your row numbering consistant and in ascending order. The cloned row will always be the last one, regardless of which one was clicked, and the new row will always be placed at the end, after it.
Changed the indexing to use the last row's index as the base for the new row and use a regular expression to determine it - with the table being ordered now, you can always count on the last row to have the highest index. By using the regular expression /^(.+)(\d+)$/i, you can split up the index value into "everything before the index" and "the index (i.e., on or more numbers, at the end of the value)". Then, you simply increment the index by 1 and reattach it, for the new value. Using the regex approach also allows you to easily adapt, it there ever get to be more than 9 rows (i.e., double-digit indices).
Updated both the id and name attributes for each input - I assumed that you would want the id and name attributes to be the same for each individual element, based on the initial row, and, you were only updating the id in your code, which would have caused problems when sending the data.
Changed $("input:date") to $("input[type='date']) - as Mouser pointed out, this was really the core reason why your code was failing, initially. All of the other changes will help you avoid additional issues in the future or were simply "code quality"-related changes.
So . . . those were the major updates. :) Let me know if I misunderstood what you were trying to do or if you have any questions.
$("document").ready(function() {
$('#productanddates').on('click', ':button', function () {
var lastRow = $(this).closest('table').find("tr:last-child");
var cloned = lastRow.clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
var regIdMatch = /^(.+)(\d+)$/;
var aIdParts = id.match(regIdMatch);
var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);
$(this).attr('id', newId);
$(this).attr('name', newId);
});
cloned.find("input[type='date']").val('');
cloned.insertAfter(lastRow);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blue-bar ta-l">
<div class="container">
<h1>Submit Your Insurance Renewal Date(s)</h1>
</div>
</div>
<div class="grey-bar">
<div class="container">
<div class="rounded-box">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" autocomplete="off" required />
</div>
<div>
<label for="name">Renewal Dates</label>
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="5" id="productanddates" class="border">
<tr>
<td>
<select name="insurance_type1" id="insurance_type1">
<option></option>
<option>Car</option>
<option>Home</option>
<option>Van</option>
<option>Business</option>
<option>GAP</option>
<option>Travel</option>
</select>
</td>
<td>
<input type="date" name="renewal_date1" id="renewal_date1" />
</td>
<td>
<input type="button" name="button1" id="button1" value="+" />
</td>
</tr>
</table>
<div>
<label for="telephone_number">Contact Number</label>
<input type="tel" id="telephone_number" name="telephone_number" pattern="\d{11}" autocomplete="off" required />
</div>
<div>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" autocomplete="off" required />
</div>
<div>
<input name="submit" type="submit" value="Submit" class="btn">
</div>
</div>
cloned.insertAfter(thisRow).find('input[type="date"]').val('');
I have the following HTML:
<div class="pane">
<h3>
<input type=hidden id="comm_id" value="{$comment.id}">
<label id="comm_name" onclick="this.style.display='none';document.getElementById('comm_name_edit_view').style.display='';document.getElementById('comm_name_edit').value=this.innerHTML;">{$comment.writer_name}</label>
<div id="comm_name_edit_view" style="display:none;">
<input type=text id="comm_name_edit" value="{$comment.writer_name}">
<button onclick="this.parentNode.style.display='none';document.getElementById('comm_name').innerHTML=getElementById('comm_name_edit').value;document.getElementById('comm_name').style.display='';">حفظ</button>
</div>
</h3>
<p>
<label id="comm_content" onclick="this.style.display='none';document.getElementById('comm_content_edit_view').style.display='';document.getElementById('comm_content_edit').value=this.innerHTML;">{$comment.comment}</label>
<div id="comm_content_edit_view" style="display:none;">
<textarea type=text id="comm_content_edit">{$comment.comment}</textarea>
<button onclick="this.parentNode.style.display='none';document.getElementById('comm_content').innerHTML=getElementById('comm_content_edit').value;document.getElementById('comm_content').style.display='';">حفظ</button>
</div>
</p>
<p>delete | approve | spam</p>
</div>
and the following jQuery (I'm bad at jQuery)
jQuery(function(){
$(".pane:even").addClass("alt");
$(".pane .btn-delete").click(function(){
var x=SOMETHING;
$(this).parents(".pane").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow")
return false;
}); ..... etc
In the var x=SOMETHING;, I want to be able to get the value of the input box with ID of comm_id in that pane. Is it somehow possible?
Thank you.
You can get the input by using .closest() to get to the <div class="pane"> then .find() the input inside, like this:
$(".pane .btn-delete").click(function(){
var x = $(this).closest(".pane").find(".comm_id").val();
//use x
//animations...
});
Note the change of id to class to be valid for multiple panes, your <input> should look like this:
<input type="hidden" class="comm_id" value="{$comment.id}">
var x = $("#comm_id").val();
EDIT:
actually, you don't even need to select it by ID: you could just use
var x = $( "input[type=hidden]", $( this ).parents(".pane") ).val();
this would solve the problem if you have several fragments of code like that.