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.
Related
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
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
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());
});
I'm working on a dynamic form where you can add or delete fields, Here you can find the fiddle
The first button you find is Add Metric. From this the code generates:
Input Field Metric
Button Add Tag
Inside this field a user can add a tag with the button Add Tag, generated when you click add Metric. When you click Add Tag button, two fields are generated:
Input Field Id
Input Field Value
The Html code that I need to generate in order to serialize the entire form (this is not however the question point) will result like this:
<input type="text" name="metrics[0][name]" value="Text 0"> // Metric
<input type="text" id="TagId0" name=" "> //Tag Id
<input type="text" id="TagValue" name="metrics[0][tags][][0]">
Problem:
I need that (when I fill the field with id="TagId0") the value I select will go immediately to the field name with id="TagValue". This field must result like this:
Consider I write on TagId0 the word "hello", field will become:
<input type="text" id="TagValue" name="metrics[0][tags][hello][0]">
How, if it's possible, it can be done?
Thanks
You can use the change method to detect a change in the fields value. Then use the attr method to change the name. Hope I understood correctly. Here is the modified JSFIDDLE.
$(document).on('change', '#InputsWrapper .inputID', function(){
thisVal = $(this).val();
thisName = $(this).siblings('.inputVal').attr('name');
newName = thisName.replace('[tags][', '[tags][' + thisVal);
$(this).siblings('.inputVal').attr('name', newName);
});
Don't forget to press enter after change the field value :)
Edit: I also added two classes to the fields you are appending. .inputID and .inputVal. I hope this helps!
you can write id of field something like TagId-0 and some common class like tagfield,so that u can split the value to get the index an then access it using the class
$(".tagfield").keypress(function() {
var id=parseInt($(this).attr("id").split("-"));
$(this).siblings().attr("name","metrics["+id+"][tags]["+$(this).val()+"][0]");
});
In HTML & JS, how do you make a textfield that has grayed out text telling the user what the field is for that goes away when the user clicks on the field?
For example, in firefox the search field in the top right hand side says which search engine it uses when there's nothing entered, then once you click it's an empty textfield, but if you leave it blank and remove focus from the textfield then the grayed out text is back again.
Is there a name for this behavior? Also, is it possible to do in pure css without the use of js to do the on focus / on blur events?
The effect that you are referring to is often called the placeholder effect. Within HTML5 this effect is possible within certain browsers by simply placing the new attribute 'placeholder' within your input tag. Such as...
<input type='text' placeholder='Place Holder Text'/>
<input type='text'/> <!-- Example with no title-->
<input type='text' title='Your title'/>
This can also be done in JavaScript using CSS by setting a style for an active class and toggling the active style along with the item's title tag. Such as ...
$(document).ready(function(){
// Select all input fields. (You will probably want to filter this down even further).
var inputs = $('input[type=text]');
// Set all the inputs to the title value.
inputs.each(function(){
$(this).val($(this).attr('title')).addClass('unfocused'); // Styling Class for inputs.
});
// When the user focuses on an input
inputs.focus(function(){
var input = $(this);
if(input.val() == input.attr('title')){
$(this).removeClass('unfocused').val('');
}
});
// When the user loses focus on an input
inputs.blur(function(){
var input = $(this);
if(input.val() == ''){ // User has not placed text
input.val(input.attr('title')).addClass('unfocused');
}
});
});
The tested function can be seen here: http://www.jsfiddle.net/F8ZCW/5/
This behavior is on my URL shortener site: http://relk.in
The basic idea is when the onfocus event fires, you modify the CSS of the textfield to a normal class, and then onblur, you re-apply the previous class.
And no, you cannot do this in pure CSS.
Example:
var textfield = document.getElementById('someTextField');
textfield.onfocus = function() {
this.className = this.className.replace('oldClassName', 'newClassName');
};
textfield.onblur = function() {
this.className = this.className.replace('newClassName', 'oldClassName');
}