How to get specific ID from multi ID? - javascript

In my case, I want to make plus or minus button with add or minus to count number into text box. I can do it. But I've got the error. There have multi row with same design but different ID (I mean working with auto increment ID). When I click on plus button of top or middle row but it doesn't work on it's own row. It's always work on the last row.
Here is my Screenshot
Here is my HTML in JQuery Code. When Click on Add button at right top corner, this code work. It's doesn't the problem.
<input id="qty1" type="text" class="form-control dateadd" style="border- radius:0px;" name="count_date[]" value="0">
Here is my processing JQuery codes.
var test;
$('.dateadd').each(function() {
var test = this.id;
console.log("ID is",test, "Hello, world!");
});
$(document).ready(function(){
$('.plus').click( function() {
var counter = $(test).val();
counter++ ;
$(test).val(counter);
});
});
$(document).ready(function(){
$('.minus').click( function() {
var counter = $(test).val();
counter-- ;
$(test).val(counter);
});
});
Here is my Row HTML Code
<div class="col-sm-5" style="padding-right:0;">
<div class="input-group">
<span class="input-group-btn">
<a class="btn btn-default plus" type="button" style="background-color:#7ec1cb;color:#fff;border-radius:0px;">+</a>
<a class="btn btn-default minus" style="color:#7ec1cb;border-radius:0px;">-</a>
</span>
<input type="text" class="form-control qty" style="border-radius:0px;" name="count_date[]" value="0">
</div>
</div>
Here is my Row Add Jquery + HTML Code
var perDayHtml = '<div class="col-sm-5" style="padding-right:0;">'+
'<div class="input-group">'+
'<span class="input-group-btn">'+
'<a class="btn btn-default plus" type="button" style="background-color:#7ec1cb;color:#fff;border-radius:0px;">+</a>'+
'<a class="btn btn-default minus" style="color:#7ec1cb;border-radius:0px;">-</a>'+
'</span>'+
'<input id="qty1" type="text" class="form-control dateadd" style="border-radius:0px;" name="count_date[]" value="0">'+
'</div>'+
'</div>'
$("#optionBox").on('click', '.addPerDay', function(){
$('.remove').prop('disabled', false);
if (rowNo<maxi && rowNo<minusmaxi) {
rowNo++;
plan++;
$(".perDay:last").after(perDayHtml.replace(/qty1/g,"qty" + rowNo));

I guess that you've plus/minus button in same div with the dateadd input so you could just go up to the parent div then find the dateadd input :
$(document).ready(function(){
$('body').on('click', '.plus', function() {
var parent = $(this).closest('div');
var counter = parseInt(parent.find('.qty').val());
counter++ ;
parent.find('.qty').val(counter);
});
$('body').on('click', '.minus', function() {
var parent = $(this).closest('div');
var counter = parseInt(parent.find('.qty').val());
counter-- ;
parent.find('.qty').val(counter);
});
});
NOTE 1: NO need for multiple ready function.
NOTE 2: You should use event delegation .on() instead of .click() since your code is added dynamically to the DOM.
NOTE 3: Check in minus click event if the qte is greater than 0 before decreasing the counter :
counter>0?counter--:counter;
Hope this helps.
$(document).ready(function(){
$('body').on('click', '.plus', function() {
var parent = $(this).closest('div');
var counter = parseInt(parent.find('.qty').val());
counter++ ;
parent.find('.qty').val(counter);
});
$('body').on('click', '.minus', function() {
var parent = $(this).closest('div');
var counter = parseInt(parent.find('.qty').val());
counter>0?counter--:counter;
parent.find('.qty').val(counter);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div class="input-group">
<span class="input-group-btn">
<a class="btn btn-default plus" type="button" style="background-color:#7ec1cb;color:#fff;border-radius:0px;">+</a>
<a class="btn btn-default minus" style="color:#7ec1cb;border-radius:0px;">-</a>
</span>
<input type="text" class="form-control qty" style="border-radius:0px;" name="count_date[]" value="0">
</div>
<div class="input-group">
<span class="input-group-btn">
<a class="btn btn-default plus" type="button" style="background-color:#7ec1cb;color:#fff;border-radius:0px;">+</a>
<a class="btn btn-default minus" style="color:#7ec1cb;border-radius:0px;">-</a>
</span>
<input type="text" class="form-control qty" style="border-radius:0px;" name="count_date[]" value="0">
</div>
<div class="input-group">
<span class="input-group-btn">
<a class="btn btn-default plus" type="button" style="background-color:#7ec1cb;color:#fff;border-radius:0px;">+</a>
<a class="btn btn-default minus" style="color:#7ec1cb;border-radius:0px;">-</a>
</span>
<input type="text" class="form-control qty" style="border-radius:0px;" name="count_date[]" value="0">
</div>

Related

Copy attribute value of link to input value onclick

I want to copy the attribute value val="ok" of my link to an input field in my bootstrap modal :
$('#link').on('click', function() {
var x = document.getElementById("link").getAttribute("val");
$("#mail").find(".compose").value = x;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-toggle="modal" data-target="#mail" id="link" val="ok" class="btn btn-warning btn-flat" title="Mail"><i class="fa fa-envelope"></i>Link</a>
<input class="form-control" placeholder="To:" class="compose" value="" />
You should create custom data attribute data-val for example and then you can access it like yourElem.dataset.val
var a = document.getElementById('link');
a.addEventListener('click', function() {
var val = a.dataset.val;
document.querySelector('.compose').value = val;
})
<a data-toggle="modal" data-target="#mail" id="link" data-val="ok" class="btn btn-warning btn-flat" title="Mail"><i class="fa fa-envelope"></i>Link</a>
<input class="form-control compose" placeholder="To:" value="" />
You can also use JQuery use data()
$('a').click(function() {
$('input').val($(this).data('val'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-toggle="modal" data-target="#mail" id="link" data-val="ok" class="btn btn-warning btn-flat" title="Mail"><i class="fa fa-envelope"></i>Link</a>
<input class="form-control compose" placeholder="To:" value="" />

jQuery .closest failed to find parent's input value

I have this HTML structure :
<input type="text" name="quantity" class="form-control quantity" value="1" min="1" max="10" maxlength="2" size="2">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number btn-plus p-l-10 p-r-10">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
and also I have this jquery script :
<script>
$(document).ready(function(){
$(document).on("click", ".btn-plus", function() {
event.preventDefault();
var quantity = $( this ).closest( ".quantity" ).val();
alert (quantity);
});
});
</script>
theoretically, I can get value of input text once the btn-plus is clicked, but I still get undefined value as result.
how to get the input value of .quantity using .closest? thank you
.closest() is used to find a matching ancestor element, in your case the input element is the previous sibling of the buttons parent
$(document).ready(function() {
$(document).on("click", ".btn-plus", function(event) {
event.preventDefault();
var quantity = $(this).parent().prev(".quantity").val();
alert(quantity);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="quantity" class="form-control quantity" value="1" min="1" max="10" maxlength="2" size="2">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number btn-plus p-l-10 p-r-10">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
$(document).ready(function() {
$(document).on("click", ".btn-plus", function(event) {
event.preventDefault();
var quantity = $(this).closest("span").prev().val();//use closest span and prev to get input
alert(quantity);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="quantity" class="form-control quantity" value="1" min="1" max="10" maxlength="2" size="2">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number btn-plus p-l-10 p-r-10">
<span class="glyphicon glyphicon-plus">asdasdasdas</span>
</button>
</span>
Use .closest() span to get the parent span. Since input is before span use .prev()
According to the JQuery website it appears as though the closest function acts similarly to the parents function in that it only looks at the ancestors of the element you are targeting.
https://api.jquery.com/closest/#entry-longdesc
As the input tag is not a parent of the button tag then the closest function will not find it.
Utilize a combination of parent and sibling or similar to target the input tag.

showing a button if there are no dynamically created form fileds available

i have a field with 'add' and 'remove' field options and my problem is if someone click remove button at first time then there is nothing left. however i created a another button and hide it by this code.
$('#more_fields').hide();
is that possible to show this button when there is no field or no button with deleteMe class available
i'm using this code for delete fields.
$(document).on("click",".deleteMe", function(){
$(this).closest(".addform").remove();
});
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="addform"><div class="input-group"> <label for="Services">Services '+room+'</label> <input type="text" class="form-control" id="Services" name="serve[]" style="max-width: 148px;" placeholder="Add Services"> <span class="input-group-btn" > <button class="btn deleteMe" style="">×</button> <button class="btn btn-success pull-right" onclick="add_fields();" type="button"><i class="fa fa-plus"></i></button> </span> </div></div>';
objTo.appendChild(divtest)
}
//]]>
$(document).on("click",".deleteMe", function(){
$(this).closest(".addform").remove();
});
$('#more_fields').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form class="form-inline">
<div class="">
<div class="form-group">
<div id="room_fileds" class="text-center">
<div class="addform">
<!--<label for="qualification">Services 1</label>
<input type="text" class="form-control" id="Service" style="" placeholder="Add Services">
-->
<div class="input-group">
<label for="Services">Services 1</label>
<input type="text" class="form-control" id='Services' name="serve[]" style="max-width: 148px;" placeholder="Add Services">
<span class="input-group-btn" >
<button class="btn deleteMe" style="">×</button>
<button class="btn btn-success pull-right" onclick="add_fields();" type="button"><i class="fa fa-plus"></i></button>
</span>
</div>
<span id="err_quali" style="color:red;display:none;font-size:13px;padding-left:105px;">Enter only Chars</span>
</div>
</div>
<input type="button" class="btn btn-success btn-sm" id="more_fields" onclick="add_fields();" value="Add Services" />
</div>
</div>
</form>
on delete do like
room -= 1;
than if at some point you do
if(room===0) { /*here show your button */ }
I've noticed that you use ID for buttons like #err_quali, #Services... Don't. you're going to have load of duplicate IDs on the page which is wrong. Use classes instead.
jsBin demo
var rooms = 1;
var c = 1;
var $roomsWrapper = $("#room_fileds"); // the parent
var $room = $(".input-group").clone(); // Store a group
$('#more_fields').hide();
$(".form-inline").on("click", ".deleteMe", function(ev) {
ev.preventDefault();
rooms -= 1;
$(this).closest(".input-group").fadeOut(300, function(){
$(this).remove();
});
$('#more_fields').toggle( !rooms );
}).on("click", ".addField, #more_fields", function(ev) {
ev.preventDefault();
rooms += 1;
c += 1;
var $klon = $room.clone();
$klon.find(".groupNum").text(c);
$roomsWrapper.append( $klon );
});
.err_quali{
color:red;
display:none;
font-size:13px;
padding-left:105px;
}
.form-control{
max-width: 148px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- FORM -->
<form class="form-inline">
<div id="room_fileds">
<!-- CLONABLE FIELD HELPER -->
<div class="input-group">
<label for="Services">Services <span class="groupNum">1</span></label>
<input type="text" name="serve[]" placeholder="Add Service">
<span class="err_quali">Enter only Chars</span>
<span class="input-group-btn" >
<button class="deleteMe btn">×</button>
<button class="addField btn" type="button">+</button>
</span>
</div>
<!-- Here jQuery appends Room group clones -->
</div>
<button id="more_fields">Add Services</button>
</form>

jQuery getting previous input value

<div class="panel-footer">
<div class="input-group">
<input id="btn-input" type="text" class="form-control input-sm chat_input" placeholder="Wpisz tutaj swoją wiadomość..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="btn-chat">Wyślij</button>
</span>
</div>
</div>
I have HTML like above. My question is how to get the input value when I click on #btn-chat. I have been trying of jQuery functions like .prev() and .prevAll() but those didn't work for me.
Given that the input element has an id attribute it should be unique, so you can select it directly without the need to traverse the DOM:
$('#btn-chat').click(function() {
var inputVal = $('#btn-input').val();
// do something with the value here...
});
If, for whatever reason, you still want to use DOM traversal you can use closest() to get the nearest common parent to both elements, and then find():
$('#btn-chat').click(function() {
var inputVal = $(this).closest('.input-group').find('input').val();
// do something with the value here...
});
If you have multiple elements in your page with the same id attribute then your HTML is invalid and you would need to change it. In that case, use class attributes to identify and select the elements.
$("#btn-chat").click(function(){
var input_values = $(this).parent().parent().find("input").val();
alert(input_values);
});
As #RoryMcCrossan has pointed out, if you have multiple elements with the same id attribute, you would need to use a class attribute instead.
$(function() {
$('.btn-chat').on('click', function() {
var val = $(this).closest('.input-group').find('input.btn-input').val();
//OR $(this).parent().prev().val();
console.log( val );
});
});
$(function() {
$('.btn-chat').on('click', function() {
var val = $(this).closest('.input-group').find('input.btn-input').val();
console.log( val );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="panel-footer">
<div class="input-group">
<input type="text" class="form-control input-sm chat_input btn-input" placeholder="Wpisz tutaj swoją wiadomość..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm btn-chat">Wyślij</button>
</span>
</div>
</div>
<div class="panel-footer">
<div class="input-group">
<input type="text" class="form-control input-sm chat_input btn-input" placeholder="Wpisz tutaj swoją wiadomość..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm btn-chat">Wyślij</button>
</span>
</div>
</div>
<div class="panel-footer">
<div class="input-group">
<input type="text" class="form-control input-sm chat_input btn-input" placeholder="Wpisz tutaj swoją wiadomość..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm btn-chat">Wyślij</button>
</span>
</div>
</div>

Jquery - Add and remove fields dynamically - How to do it without repeating code?

I am implementing a "JQuery add/remove input fields" solution:
I need to use some JQuery plugins to make everything work. For example I use a Datepicker, SelectPicker and Autosize..
So, for the markup that's already there (without the ADD functionality) this code works:
$(document).ready(function() {
$('.autosize').autosize();
$('input, textarea').placeholder();
$('.datetimepickaa').datetimepicker({
pickTime: false
});
$('.selectpicker').selectpicker();
// Remove the specific row
$("button.removee").click(function(){
$(this).closest(".conteiner").remove();
});
});
The problem is that when I try to add the ADD functionality, the jquery plugins don't work for the new elements, so I have to repeat the calls inside the add code to make it work:
$(document).ready(function() {
$('.autosize').autosize();
$('input, textarea').placeholder();
$('.datetimepickaa').datetimepicker({
pickTime: false
});
$('.selectpicker').selectpicker();
// Remove the specific row
$("button.removee").click(function(){
$(this).closest(".conteiner").remove();
});
// ADD FUNCTIONALITY
$("#add").click(function() {
var row = '\
<div class="form-group conteiner">\
<div class="row">\
<div class="col-md-2">\
<label for="date">Date:</label>\
<div class="input-group date datetimepickaa" id="datetimepickerloop" data-date-format="YYYY/MM/DD">\
<input type="text" class="form-control datetimepickaa" placeholder="Enter the date..." data-date-format="YYYY/MM/DD" />\
<span class="input-group-addon">\
<span class="glyphicon glyphicon-calendar"></span>\
</span>\
</div>\
</div>\
<div class="col-md-9">\
<label for="notes">Notes:</label>\
<textarea class="form-control autosize" id="" name=""></textarea>\
</div>\
<div style="" class="col-md-1">\
<button type="button" class="removee btn btn-primary btn-md pull-right" style="margin-top:25px">\
<span class="glyphicon glyphicon-remove"></span> Delete\
</button>\
</div>\
</div>\
</div>';
$("#wrapper").append(row);
// REPETITION OF THE CODE ABOVE!!!!!! //////////////////////////////
$('.autosize').autosize();
$('input, textarea').placeholder();
$('.datetimepickaa').datetimepicker({
pickTime: false
});
$('.selectpicker').selectpicker();
// Remove the specific row
$("button.removee").click(function(){
$(this).closest(".conteiner").remove();
});
});
});
Do you have any clue on how to do that the best way without repeting any code?
Thank's in advance!!
Extract them into a function and call that function?
function initializeThings()
{
$('.autosize').autosize();
$('input, textarea').placeholder();
$('.datetimepickaa').datetimepicker({
pickTime: false
});
$('.selectpicker').selectpicker();
// Remove the specific row
$("button.removee").click(function(){
$(this).closest(".conteiner").remove();
});
}
$(document).ready(function() {
initializeThings();
// ADD FUNCTIONALITY
$("#add").click(function() {
var row = '\
<div class="form-group conteiner">\
<div class="row">\
<div class="col-md-2">\
<label for="date">Date:</label>\
<div class="input-group date datetimepickaa" id="datetimepickerloop" data-date-format="YYYY/MM/DD">\
<input type="text" class="form-control datetimepickaa" placeholder="Enter the date..." data-date-format="YYYY/MM/DD" />\
<span class="input-group-addon">\
<span class="glyphicon glyphicon-calendar"></span>\
</span>\
</div>\
</div>\
<div class="col-md-9">\
<label for="notes">Notes:</label>\
<textarea class="form-control autosize" id="" name=""></textarea>\
</div>\
<div style="" class="col-md-1">\
<button type="button" class="removee btn btn-primary btn-md pull-right" style="margin-top:25px">\
<span class="glyphicon glyphicon-remove"></span> Delete\
</button>\
</div>\
</div>\
</div>';
$("#wrapper").append(row);
initializeThings();
});

Categories