based on tutorial from here ,I'm trying to make some fields which can dynamically be added by a button an removed by another button. It almost works fine except that another group of fields that supposed to be created dynamically as well is not adding anything.
Here's what i did at codepen.
<div class="field_wrapper">
New Group
</div>
<script>
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div>X<table id="add_on_table"><tbody><tr><td><label class="field">Group Name</label><input type="text" name="product_addon_name[]"></td><td><input type="checkbox" name="product_addon_required[]"> Mark as Required</td></tr><tr><td><label class="field">Group Description </label><textarea name="product_addon_description[]"></textarea></td></tr><tr><table><thead><tr><td>Option Label</td><td>Option Price (RM) </td></tr></thead><tbody class="addonoption"><tr><td><input type="text" name="product_addon_option_label[]"></td><td><input type="text" name="product_addon_option_price[]"></td><td>X</td></tr> </tbody><tfoot><tr><td><input type="button" class="add_option" value="New Option"></td></tr></tfoot></table></tr></tbody></table></div>'; //New input field html
var AddRow = $('.add_option'); //Add button selector
var RowWrapper = $('.addonoption'); //Input field wrapper
var rowHTML = '<tr> <td><input type="text" name="product_addon_option_label[]"></td><td><input type="text" name="product_addon_option_price[]"></td><td>X</td></tr>';
var x = 1; //Initial field counter is 1
$(AddRow).click(function(){ //Once add button is clicked
$(RowWrapper).append(rowHTML); // Add field html
});
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});</script>
In reference to what I did in the linked codepen, the fields generated OK when pressed the 'New Group' link. However, the button 'New Option' does not create anything once clicked. You can see in the JS section i write some code to create field, but it's just not working. Any idea why? Btw, i'm quite noob at javascript/jquery, so, sorry if it's just a stupid mistake. Thanks in advance!
You need to use event delegation with the .add_option elements too. Since they are created after the DOM is initially rendered, your click handler does not attach to anything. You use event delegation for the .remove_button, so you can copy that syntax to make it work:
$(document).on("click", ".add_option", function(){ //Once add button is clicked
$(this).closest("table").find(".addonoption").append(rowHTML);
});
Also, I noticed that your selector is potentially messed up too because if you have multiple groups, it will add the html to each one of them. If this is the intended behavior, you can change the selector to $(".addonoption").append(rowHTML), otherwise, the above code will work for you!
The problem is that when you try to add a click handler to AddRow, your button does not exist yet. Instead of creating a handler to AddRow, you need to use the .on() function. Example:
$(".field_wrapper").on("click", ".add_option", function() {alert("foo");});
Explanation:
.field_wrapper as a selector already exists when you call on
click is the event you intend to handle
.add_option is a selector which will apply to existent and not yet existent elements inside .field_wrapper that match .add_option
the function is the event handler to be executed
Related
im using select2 and try to create a reset button for each select. i have 6 select.
my script is like this
$('.deggre').on('change', function() {
var deggre = $( this ).val();
var span = $("#dropdownMenu1").find('span').clone(); // Copy 'X' span.
$("#dropdownMenu1").text(deggre); // Insert text first.
$("#dropdownMenu1").append(span); // Then, append the 'X' span.
if($(this).val() == "")
$('#dropdownMenu1').css({"display": "none"});//value is none then hide
else
$('#dropdownMenu1').css({"display": "inline-block"});//have value then show
});
$("#dropdownMenu1").click(function(){
$(".deggre").val("");
});
my script didnt work for this case. how to solve this problem?
i need to show the button when we choose option on select2, and give innerHtml to the button. and then when the button click, its will reset his own select then the button is gone cause it didnt get the value.
heres my jsfiddle
https://jsfiddle.net/acvxeq8x/2/
You need to trigger the change
$("#dropdownMenu2").click(function(){
$(".position").val("").trigger('change');
});
I have updated your fiddle: https://jsfiddle.net/acvxeq8x/3/
Here is the simplified and minimal version of your code which is pretty straight forward. The code below seems long because of comments added within for explanation. Hope you will ignore them once you understand.
HTML Changes
<div class="wrap">
<!--Remove everything within wrap div and keep one copy of button in js to dynamically
construct the button tag-->
</div>
New CSS added
button.btnspl{
margin:10px;
/*Bit styling for dynamically created buttons*/
}
JS Changes
//Bind single change event to all your select element
$('.deggre,.position,.year').on('change', function() {
var ctrl=$(this); //reference for current element
var ctrlClass=ctrl[0].classList[0]; //get the first class which will be the class given
//to your original select element like deggre, position, year etc.,
$('button.btnspl[data-control="'+ctrlClass+'"]').remove();
//Since your select element is single select type, I hope you want to keep only one tag
//for each select. So, you remove other tags with above line
if(ctrl.val() == "")return; //return if value is empty, you aren't creating anything
var btn=$('<button class="btn btn-grey btnspl" type="button"><span class="glyphicon glyphicon-remove"></span></button>');
//Button copy from your wrap div
var option = $('<span>'+ctrl.val()+'</span>');
//get the selected option and place it in span
var span = $(deggre).insertBefore(btn.find('span'));
//insert the above created span before the glyphicon-remove in button
btn.attr('data-control',ctrlClass);
//the created button should have information about the control which created it
//so wrapping the ctrlClass [deggre, year, position] into data-* attribute of created button
//this will be used to remove particular button and clear its respective select,
//on different scenarios
$('.wrap').append(btn);
//append the button to .wrap div
});
//attaching close click event to glyphicon-remove.
//Read about event-delegation for dynamically created elements
//button is dynamically created here
$('.wrap').on('click','.glyphicon-remove',function(){
var ctrl=$(this).closest('.btn');
//get the parent of the clicked remove icon using closest
var ctrlClass=ctrl.attr('data-control');
//get its data-control attribute added during creation
$('.'+ctrlClass).val("").trigger('change');
//empty its value and trigger change
ctrl.remove();
//remove the control
})
JSFiddle DEMO
I am trying to create input fields with button. But what I want is, when input field is created, I want hide created input field with the same button. I tried slideToggle function, but that didn't worked very well.
<button type="button" id="addEmail" "class1"></button>
$('#addEmail').one('click', function () {
var dummy = '<input type="text">';
$('.email').after(dummy); //creating input after class 'email'
$(this).addClass('less-inputs'); //Changing buttons css
});
The most concise way would be to create a jQuery context to represent your dummy element instead of a mere HTML string.
Something like:
var $dummy = $('<input type="text">');
$('.email').after($dummy);
$dummy.addClass('less-inputs');
Or even shorter:
$('<input type="text">')
.addClass('less-inputs')
.insertAfter($('.email'));
You can add the input within the HTML and simply show/hide it on button click.
If you want to create it dynamically you can add an ID to the input to check its existence. If the input exists you remove it, otherwise you add it.
A table column displays student id numbers as follows:- (PHP code)
echo "<td><b><a href = '#'><h1>".$res['studid']."</h1></a></b></td>";
Below the table there is an input box to enter student id
I want to add the value of $res variable into the input box when the user clicks the above link.
That value will be later used to search the result of that particular student
How to achieve this with Javascript?
var studentLinks=document.querySelectorAll('td>b>a>h1');
for(var i=0;i<studentLinks.length;i++){
studentLinks[i].parentNode.addEventListener('click',function(){
document.getElementById('yourInputField').value=this.children[0].innerHTML;
});
}
Non-jQuery way of applying this functionality to all elements.
By the way, the a element is then non-essential, so it could as well be removed and td>b>h1 be written as the selector instead.
Anyways, the above JavaScript is applied to all links. You can also put an e inside the brackets after function and at the top of the function block add e.preventDefault(); to make absolutely sure that the page doesn’t redirect anywhere.
var link = document.getElementById('studentId');
var input = document.getElementById('search');
link.addEventListener('click', function() {
input.value = this.innerText;
});
<td><b><h1>Some text</h1></b>
</td>
<input type="text" id="search">
Well a Jquery way...
$("#table a").click(function(){
$("#input").val($(this).find('h1').text());
});
So I have this table that I want to make editable. In order to do so, I have a simple event listener that removes the text from the td element and appends a input field with that text as the value. The value of that text field is then appended to the td once the text field loses focus.
The problem is it fires when the user, for example, tries to highlight and delete the text (click).
I changed the selector to exclude the specific input field's class, but to no avail.
Javascript:
$(function() {
$('.text_field:not(.remove_text)').click(function() {
var text = $(this).text().trim(),
length = text.length;
$(this).empty()
.append("<input type='text' class='remove_text' size='"+length+"' value='"+text+"' />")
.find('.remove_text')
.focusout(function() {
$(this).closest('td').empty().append($(this).val());
})
.focus();
});
});
Here is a fiddle to show what I mean.
Is there something wrong with the selector or something?
An easy solution would be to add some logic to prevent emptying the table cell if it already contains an input element.
$('.text_field:not(.remove_text)').click(function() {
if( $(this).find('input').length > 0 ) {
return;
}
// your existing code
}
Here is a working example JS Fiddle
The selector is only used once for attaching the event listener. If you want to check the condition every time, it might be better to put it inside the handler:
$('.text_field').click(function(e) {
if ($(e.target).is(".remove_text") || $(e.target).closest(".remove_text").length > 0) return;
//Otherwise, execute code
});
Fiddle Here: http://jsfiddle.net/5uxf6yy7/3/
I was wondering if I could get some help with jquery. This is the html I have now:
http://jsfiddle.net/spadez/9sX6X/4/
<form name="input">
<input id="current" type="text" name="content" placeholder="content">
<input type="submit" value="Add" id="add">
</form>
What I want to do is when the user clicks "add" and as long as the input field isnt empty, I want to do the following:
Change that input field id to "accepted" and remove the add button
next to it and replace it with a remove button
Add an input field below the original one with the id to "current"
with an add button next to it
I want this process to happen every time the add button is clicked so more and more input boxes can spawn under each other. As far as I got was trying to spawn input boxes but even that doesn't work.
function addField(){
$('#add').append('<input type="text" name="myinput" />');
return false;
}
Can anyone please show me how this should be achieved.
I think it isn't a good solution to clone existing elements every time. Instead I would suggest cloning ... well... clones )) The original input and button remain the same, only visually shifted.
Is this behavior needed? - http://jsfiddle.net/skip405/9sX6X/6/
Use before()
$('#add').before('<input type="text" name="myinput" />');
since you need to append the new input just before your submit button (and not into it, which is not possible here, since it's an input element)
A working example http://jsfiddle.net/steelywing/9sX6X/12/
$('form').on('click', '.add', function () {
var row = $(this).closest('div'),
new_row = row.clone();
row.find('input:text').addClass('accepted');
row.find('.add')
.removeClass('add')
.addClass('remove')
.val('Remove');
new_row.find('input:text').val('');
row.after(new_row);
}).on('click', '.remove', function () {
$(this).closest('div').remove();
});