elow is the code i am using i am able to add new input box wen i click but it should stop adding based on the user input like no. of user-entered as 4 based on that add input box should stop
in below example:-$bookcount is user input field which comes from html input box
var i = 1;
if(i>$(bookcount))
{
$('#add').click(function()
{
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="title[]" </td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
}});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
**strong text** {
alert(data);
$('#add_name')[0].reset();
}
});
});
Couple of issues to note:
Assuming bookcount is found from $("#bookcount") then you'll need to get the .val() and convert it to a number (as "10"<"2")
Check against bookcount value inside the click event:
var i = 1;
var bookcount = $("#bookcount");
$('#add').click(function() {
if (i>(bookcount.val()*1)) {
// do nothing
return false;
}
i++;
$('#dynamic_field').append('<tr....
as you also have a remove function, don't forget to reduce i when removing
$(document).on('click', '.btn_remove', function(){
--i;
(in this case, I recommend something other than i, eg rowCount).
You can also do away with i (rowCount) by querying how many rows have been created dynamically:
var bookcountinput = $("#bookcount");
$('#add').click(function() {
var rows = $("#dynamic_field tr").length;
if (rows > bookcountinput.val()*1)
return;
$('#dynamic_field').append('<tr....
});
Related
EDIT: SOLVED. Thanks everyone!
I'm new to programming :D My code is below. Here is the deal: I have multiple buttons, but I want to make it so that the same thing would happen anytime any one of these buttons is clicked, but each button also has a specific value, and I also want that specific value to be printed out. My code goes through the document and looks at all the elements with "editButton" class, and correctly identifies all the buttons, but the problem is that no matter which button I press, I always get the value of the last button, because var id only gets assigned after the for loop finishes and is on the last element. I tried creating a global variable and assigning the value to it, but the result is the same. I tried ending the for loop before moving on to .done (function (data), but I got an error. Can someone help me out? Thanks!
$(document).ready(function() {
var anchors = document.getElementsByClassName('editButton');
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = anchor.value;
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records"></div>
Actually, instead of doing a huge for loop to add onclick events to your buttons, one of the best ways to do this is to listen to each button with editButton class on click() event then use $(this) which refers to the exact clicked button. After that, you can use each individual button to do whatever you want.
So your final code should be something like this:
$(document).ready(function() {
$('.editButton').click(function() {
console.log('innerHTML is:', $(this).html())
console.log('id is:', $(this).attr('id'))
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = $(this).value;
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records">
<button class="editButton" id="firstButton">button 1</button>
<button class="editButton" id="secondButton">button 2</button>
<button class="editButton" id="thirdButton">button 3</button>
<button class="editButton" id="fourthButton">button 4</button>
</div>
save the button with button = this when run the onclick function and use it
$(document).ready(function(){
var anchors = document.getElementsByClassName('editButton');
for(var i = 0; i < anchors.length; i++) {
var button;
var anchor = anchors[i];
anchor.onclick = function() {
button = this;
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function( data ) {
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+ button.value +'</p><br>';
$("#records").html(string);
});
}
}
});
https://jsfiddle.net/x02srmg6/
You need to look in to JavaScript closures and how they work to solve this.
When you add event listeners inside a for loop you need to be careful in JS. When you click the button, for loop is already executed and you will have only the last i value on every button press. You can use IIFE pattern, let keyword to solve this.
One simple way to resolve this issue is listed below.
<div id="records"></div>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var anchors = document.getElementsByClassName('editButton');
for(var i = 0; i < anchors.length; i++) {
//Wrap the function with an IIFE and send i value to the event listener
(function(anchor){
anchor.onclick = function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function( data ) {
var id = anchor.value;
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+id+'</p><br>';
$("#records").html(string);
});
}
})(anchors[i]);
}
}
});
You can read more about this in JavaScript closure inside loops – simple practical example
In your code..
var id = anchor.value;
could be
var id = anchor.id;
but I recommend you to use event delegation
If you have a html like this
<div id="buttonArea">
<a class="editButton" id="1"/>
<a class="editButton" id="2"/>
<a class="editButton" id="3"/>
.......(so many buttons)
</div>
you can code like below.
$(document).ready(function(){
$('#buttonArea').on('click', 'a.editButton', function (event) {
var anchor = event.currentTarget;
$.ajax({
method: "GET",
url: "/testedit.php",
})
.done(function(data) {
var id = anchor.id;
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+id+'</p><br>';
$("#records").html(string);
});
}
You can use getAttribute. Like:
var anchors = document.getElementsByClassName('editButton');
// Id of anchors
id_of_anchor = anchors.getAttribute("id");
Refs
EDIT
anchor.onclick = function() {
id_of_anchor = $(this).attr("id");
});
You have jQuery in your application, there is easier and more readable way to do it with jQuery;
$(document).ready(function() {
$(".editButton").each(function(a, b) {
$('#' + $(b).attr('id')).on('click', function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = $(b).attr('id');
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
});
});
});
Example: https://jsfiddle.net/wao5kbLn/
Is there a way to change my button to "remove" if i clicked the "add to stay button"
Like when i click the add button it will load the data then it will be changed to remove button because it is already added.
and if i press the remove button how can it go back to "add to your stay" button? Here is my js code and My button code
$(document).ready(function() {
$(".addons").on("click", function(event) {
event.preventDefault();
var id = $(this).data('addon-id');
console.log(id);
if (id != '') {
$.ajax({
type: "POST",
url: "Pages/addonajax",
data: {
id: id
},
success: function(data) {
console.dir(data);
if (data) {
result = JSON.parse(data);
$("#test4>span").html(result[0]['name']);
$("#test5>span").html(result[0]['price']);
$("#test2>span").append(result[0]['price']);
} else {
$('#test1').append('no records found');
}
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="bookingroom">Total: PHP 2,750.00</h3>
<h5 class="addon-taxes2">Including Taxes & Fees</h5>
<button class="addons addon-btn trans_200">ADD TO MY STAY</button>
here's the example fiddle
https://jsfiddle.net/j501fwb8/1/
It's much harder to maintain a single element that has to do multiple things based on some criteria. Instead I highly suggest using multiple elements with a Single Responsibility.
I'd also HIGHLY recommend reading Decoupling Your HTML, CSS, and JavaScript - Philip Walton (Engineer # Google)
My example would be something like:
$(document).ready(function() {
$('.js-btn-addon').on('click', function() {
var $this = $(this);
/// do whatever
var addonId = $this.data('addon-id');
$this.addClass('is-hidden');
$('.js-btn-remove[data-addon-id="' + addonId + '"]').removeClass('is-hidden');
});
$('.js-btn-remove').on('click', function() {
var $this = $(this);
/// do whatever
var addonId = $this.data('addon-id');
$this.addClass('is-hidden');
$('.js-btn-addon[data-addon-id="' + addonId + '"]').removeClass('is-hidden');
});
});
.is-hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="addons addon-btn js-btn-addon trans_200" data-addon-id = "1">ADD TO MY STAY</button>
<button class="addons addon-btn js-btn-remove is-hidden trans_200" data-addon-id = "1">Remove</button>
<br/>
<button class="addons addon-btn js-btn-addon trans_200" data-addon-id = "2">ADD TO MY STAY</button>
<button class="addons addon-btn js-btn-remove is-hidden trans_200" data-addon-id = "2">Remove</button>
<br/>
<button class="addons addon-btn js-btn-addon trans_200" data-addon-id = "3">ADD TO MY STAY</button>
<button class="addons addon-btn js-btn-remove is-hidden trans_200" data-addon-id = "3">Remove</button>
<br/>
You can change the HTML of the element to say Remove by using:
$(".addons").html('Remove');
You will have to handle the onClick method functionality accordingly though. Or you can remove the button altogether and show a different one.
You can change text after ajax call and load data, also you can add class for remove process etc.
Note: here i remove your ajax call, just put .text() on ajax success when load data
$(document).ready(function(){
$(".addons").on("click", function(event) {
var _t = $(this);
if(_t.hasClass('remove')){
_t.removeClass('remove').text('ADD TO MY STAY');
} else {
_t.addClass('remove').text('Remove');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class = "bookingroom">Total: PHP 2,750.00</h3>
<h5 class = "addon-taxes2">Including Taxes & Fees</h5>
<button class="addons addon-btn trans_200">ADD TO MY STAY</button>
You can use a class to mark the button once it has been used to add the item. Wrapping the execution code inside an if/else block lets you check whether the class exists so you can act accordingly.
See the comments in this suggested code:
$(document).ready(function() {
$(".addons").on("click", function(event) {
event.preventDefault();
var id = $(this).data('addon-id');
console.log(id);
if (id != ''){
// Tests which type of button this is (see below)
if(!this.classList.contains("isRemoveButton")){
/* Your ajax call for adding goes here */
// Changes the button text
$(this).text("REMOVE");
// Adds a class indicating which type of button this is
this.classList.add("isRemoveButton");
} else {
/* Different ajax call for removing goes here */
// Restores original button text
$(this).text("ADD TO MY STAY");
// Restores original classList state
this.classList.remove("isRemoveButton");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="bookingroom">Total: PHP 2,750.00</h3>
<h5 class="addon-taxes2">Including Taxes & Fees</h5>
<button class="addons addon-btn trans_200" data-addon-id="1">ADD TO MY STAY</button>
$(document).ready(function(){
$(".addons").on("click", function(event) {
event.preventDefault();
var id = $(this).data('addon-id');
console.log(id);
if(id != '')
{
$.ajax(
{
type:"POST",
url : "Pages/addonajax",
data:{id:id},
success:function(data)
{
console.dir(data);
if (data) {
result = JSON.parse(data);
$("#test4>span").html(result[0]['name']);
$("#test5>span").html(result[0]['price']);
$("#test2>span").append(result[0]['price']);
}
else {
$('#test1').append('no records found');
}
}
});
}
$(this).hide();
$('.remove').show();
//and write a remove property which you want.
});
$('.remove').on("click", function(){
//write your property here for remove once.
$(".addons").show();
$(this).hide();
})
});
I have try to create Dynamic Input group
My expected is
dynamic selection box[length in config var parameter] with...
Non-duplicate select option --> I check when click ,remove and append
Can click to add/remove input group
limited by var parameter
So now My actual result is
not hide will be select option in new select of previous select on append
delete select can't check the repeating after remove
But After i click some where will back to normal as i expect a little because item what i click still no update
So here for long code
Thank for viewing
var parameter =[
"A"
,"B"
,"C"
,"D"
];
$(document).ready(function(e){
$('div.multiselect').append('<div class="selectlist"></div>');
$('div.multiselect').append('<button class="btn btn-outline-light addlist">add search parameter</button>');
$('div.multiselect').append('<button class="btn btn-success search">search</button>');
addSelect();//Create first
$('div.multiselect .addlist').click(function(){
addSelect();
});
});
(function($) {
var origAppend = $.fn.append;
$.fn.append = function () {
return origAppend.apply(this, arguments).trigger("append");
};
})(jQuery);
var selectblock = function (){
var outside = $(document.createElement("div")).addClass('input-group');
var inside = $(document.createElement("select")).addClass('custom-select').on("click append",checkRepeat);
var selVal=[];
$("div.multiselect .selectlist div.input-group").each(function(){
selVal.push($(this).find("select").val());
});
if(selVal.length == parameter.length){
alert("Can't add more parameter");
return;
}
for (var i =0 ; i < parameter.length ; i++){
var option = $(document.createElement("option")).val(parameter[i]).text(parameter[i]);
if($.inArray(parameter[i], selVal) > -1){
option.attr("disabled","disabled").hide();
}
inside.append(option);
}
outside.append(inside);
outside.append($(document.createElement("input")).attr('Type','Text').addClass('form-control'));
var delbtn = $(document.createElement("button")).text("X").addClass('btn btn-danger input-group-append dellist');
delbtn.click(function(){
$(this).parent().remove();
checkRepeat;
});
outside.append(delbtn);
return outside;
};
function addSelect(){
$('div.multiselect .selectlist').append(selectblock);
checkRepeat;
}
var checkRepeat = function (){
//console.log('trigger');
var selVal=[];
$("div.multiselect .selectlist div.input-group").each(function(){
selVal.push($(this).find("select").val());
});
$(this).parent().siblings("div.multiselect .selectlist div.input-group").find("select").find("option").removeAttr("disabled").show().filter(function(){
var a=$(this).parent("select").val();
return (($.inArray(this.value, selVal) > -1) && (this.value!=a));
}).attr("disabled","disabled").hide();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="multiselect">
<script type="text/javascript">
$(document).ready(function () {
$("#submit").on("click", function () {
$(this).attr('disabled', true);
var taskid = num;
var loadnew = 1;
var guessnum = $("input[name=guessnum]:checked").val();
if (guessnum != 1 && guessnum != 2) {
alert("You could not submit an empty answer");
loadnew = 0;
location.href = "/minions/peerprediction1.php";
}
else if (loadnew == 1) {
finishedTask += 1;
}
var starttime = $("#timestart").val();
var timecost = starttime;
$.ajax({
type: "post",
url: "GameMysql.php",
data: "taskid=" + taskid + "&guessnum=" + guessnum + "&effort=" + effort + "&finishedTask=" + finishedTask + "&time=" + timecost,
success: function (data) {
}
});
});
});
</script>
<form>
<a class="button" id="submit"><span>✓</span>Submit report</a>
</form>
I want to make sure the form with same answers do not submit twice, and disable the button, but it does not truly work. For I click it twice the finished task number increased by 2
I already see the answer here Prevent double submission of forms in jQuery
and tried, but still could not make it work
Use the button element, it will provide the functionality you are after. It can be styled to look like an anchor. Less issues trying to get it working as intended across all browsers.
$("#submit").on("click",function(){
$(this).attr('disabled', true);
console.log('disabled');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" id="submit"> <span>✓</span> Submit report</button>
You should use a button instead of an anchor, anchors dont support the disabled attribute
<button id="submit">Submit Report</button>
I need to have buttons for moving up and down table rows with input's inside.
On move I need to guarantee that the input's name's and id's are changed
regarding to their new position
I've tried around on JSFiddle but couldn't get it to work: http://jsfiddle.net/vaDkF/1194/
For example I've the first row is moved down there are four changes:
<input type="text" id="id_1" name="id_1"/>
<input type="text" id="test_1" name="test_1"/>
needs to become
<input type="text" id="id_2" name="id_2"/>
<input type="text" id="test_2" name="test_2"/>
but the values need's to stay the same just need the id/name to change.
This is just a test example, in production environment I have like 20 inputs
per row.
Hope someone can help.
Try this : after rearranging the rows, call a function which will reassigne id and name to the input fields
$(document).ready(function(){
$(".up,.down").click(function(){
var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
row.insertBefore(row.prev());
} else {
row.insertAfter(row.next());
}
reAssignIdAndName();
});
reAssignIdAndName = function(){
$('table tr').each(function(index){
$(this).find('td:eq(2) input').each(function(){
//id of input element
var id = $(this).attr('id');
//get index of underscrore
var underScoreIndex = id.indexOf('_');
//take id till underscore and append your index+1 value
id = id.substring(0,underScoreIndex+1)+(parseInt(index)+1);
//assigne new id and name
$(this).attr('id',id);
$(this).attr('name',id);
});
});
};
});
Demo
This works and reAssign the position only for the 2 rows that moved :
jQuery(document).ready(function($){
$(".up,.down").click(function(){
var $this = $(this),
row = $this.parents("tr:first");
if ($this.is(".up")) {
if (row.parent().find("tr:first").get(0) !== row.get(0)) {
reAssignPosition(row.prev().find('input'));
row.insertBefore(row.prev());
reAssignPosition(row.find('input'), true);
}
} else {
if (row.parent().find("tr:last").get(0) !== row.get(0)) {
reAssignPosition(row.next().find('input'), true);
row.insertAfter(row.next());
reAssignPosition(row.find('input'));
}
}
});
function reAssignPosition($elt, up) {
var $row = $elt.parents("tr:first"),
oldPosition = parseInt($row.find('input').attr('id').replace(/(id|test)_/, '')),
newPosition, newId, newName, input = $row.find('input');
if (up) newPosition = oldPosition - 1;
else newPosition = oldPosition + 1;
$elt.each(function() {
this.id = this.id.replace(/(id|test)_(.*)/, "$1_" + (newPosition));
this.name = this.name.replace(/(id|test)_(.*)/, "$1_" + (newPosition));
});
}
});
Some refactoring can be done, I am sure, though.