i'm trying to give the user the possibility to update the values of some fields concerning him by clicking on a container named #info-client
Here I append the input areas after the click and once the #finish button is clicked the infos will then be updated.
The problem i got is that the infos were updated yet they were showed more than once ( 2 times or even 3 .. )
$("#info-client").one('click', function() {
$("#info-client").children().hide();
// liste des champs
var c1 = $('<label> Nom : </label><input type="text id="identifiant"> <br>');
var c2 = $('<label> Adresse : </label><input type="text" id="adresse"><br>');
var c3 = $('<label> Ville : </label><input type="text" id="ville"><br>');
var c4 = $('<label> Tel : </label><input type="text" id="tel"> <br>');
var c5 = $('<label> Fax : </label><input type="text" id="fax"> <br>')
var button = $('<input type="button" id="finish" value="Mettre à jour">');
$("#info-client").append(c1);
$("#info-client").append(c2);
$("#info-client").append(c3);
$("#info-client").append(c4);
$("#info-client").append(c5);
$("#info-client").append(button);
$("#finish").one('click', function() {
var identifiant = $('#identifiant').val();
var adresse = $('#adresse').val();
var ville = $('#ville').val();
var tel = $('#tel').val();
var fax = $('#fax').val();
c1.replaceWith("<h4>" + identifiant + "</h4>");
c2.replaceWith("<p> Adresse : " + adresse + "</p>");
c3.replaceWith("<p>" + ville + "</p>");
c4.replaceWith("<p>Fax : " + tel + "</p>");
c5.replaceWith("<p> Tel :" + fax + "</p>");
});
});
See what's happening is once you've clicked #info-client for the first time, it puts all of the form elements INSIDE #info-client. So when you click on any of the input boxes, including #finish (all of which are inside #info-client), it triggers the on-click function (I'm assuming you misspelled on()) and hides and adds everything again.
What you could do, instead, is have the form initially on the screen but hidden from view. When a certain trigger button is clicked, rather than writing the form elements to screen, you simply show the form. This way, you're not rewriting the form every time #info-client is hit, and it'll also be easier to manage #finish.
See if that helps.
Related
Hi I want to create a stamp script and I want the user to enter his name and address in three fields,
then he should see the fields later in the stamp edition?
I have 3 input fields where the user can give in his data,
now i will give this data in a new class. This is what i have:
window.onload = function() {
$( "#Text1" )
.keyup(function() {
var value = $( this ).val();
$( ".ausgabe" ).text( value );
})
.keyup();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Text1">
<input type="text" id="Text2">
<input type="text" id="Text3">
<div class="ausgabe"></div>
It looks like you want to mimic what the user is typing in the text inputs and show it in ausgabe. If that's what you want, then you can tie the keyUp event to each of the inputs.
$(input [type='text']).keyUp(function() {
var value = $(this).val();
$('.ausgabe').text(value);
}
But this will overwrite .ausgabe every time text is entered into a different input.
You could get the value of .ausgabe every time keyUp fires and pre-pend that value:
So you may want to have a button that renders each input's value into .ausgabe:
<button>.click(function() {
$(input[type="text"]).each(function() {
var boxText = $(this).val(); //text box value
var aus = $('.ausgabe').text(); //ausgabe value
$('.ausgabe').text(boxText + ' ' + aus); //combine the current text box value with ausgabe
})
})
As you have not made it very clear what you are trying to accomplish, I am providing a simple example that might send you down the right path.
$(function() {
function updateDiv(source, target) {
var newVal = "";
source.each(function() {
newVal += "<span class='text " + $(this).attr('id').replace("Text", "item-") + "'>" + $(this).val() + "</span> ";
});
target.html(newVal);
}
$("[id^='Text']").keyup(function(e) {
updateDiv($("input[id^='Text']"), $(".ausgabe"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Text1">
<input type="text" id="Text2">
<input type="text" id="Text3">
<div class="ausgabe"></div>
Since you already seem to understand .html() and .text(), we can look at the Selector. The one used will select all elements with an ID Attribute of Text in the beginning of the string. See More: https://api.jquery.com/category/selectors/attribute-selectors/
I have four radio buttons, the last being an option for "other." Clicking this radio button reveals a hidden text field so the user can explain further. This is part of a larger form that creates an email based on the options the user chose. Basically, the four radio buttons/other field need to be combined so the user's answer to that section shows up in the email, whether they pick a radio button or type in their own response. Here's my HTML:
<h1>Reason</h1>
<input type="radio" name="reason" class="reason" value="Customer requesting escalation" onclick="document.getElementById('hiddenOtherField').style.display='none'" checked>Customer requesting escalation<br>
<input type="radio" name="reason" class="reason" value="Workaround lost" onclick="document.getElementById('hiddenOtherField').style.display='none'">Workaround lost<br>
<input type="radio" name="reason" class="reason" value="Resolution overdue" onclick="document.getElementById('hiddenOtherField').style.display='none'">Resolution overdue<br>
<input type="radio" name="reason" class="reason" id="otherRadioBtn" onclick="document.getElementById('hiddenOtherField').style.display='block'">Other...<br>
<div id="hiddenOtherField" style="display: none">
<input type="text" name="reason" id="otherFreeTextField" placeholder="Please explain...">
</div><br>
I'm getting the selected value of this "Reason" section from jQuery:
$(".reason:checked").val()
But when "Other" is checked, the value of $(."reason") is "on" instead of whatever they typed. I have no idea why or how or where the word "on" comes from (it's nowhere in my code). I know I'm missing something but I don't know what. How would I make it so if the user selects the "other" radio button, whatever they type into the text field becomes the value for "reason"? I've tried a bunch of different if statements, but it's been hours and nothing is working. Please help! Thanks!
Edit - here is the Javascript code I'm using to display my values. Again, this is all a custom HTML form used to create an email based on the options the user chose. All of the other things here I'm getting the values of are working because they're straightforward.
function generateEmail() {
var emailTo = $("#teamName").val();
var emailCC = $("#CC").val();
var emailSubject = $("#ticketNumber").val();
var emailBody = "Issue: " + $("#issue").val() + "%0A%0ACustomer Contact Information: " + $("#contactInformation").val() + "%0A%0ARequested Action: " + $(".requestedAction:checked").val() + "%0A%0AReason: " + $(".reason:checked").val() + "%0A%0AWorkaround Available? " + $(".workaround:checked").val();
location.href = "mailto:" + emailTo + "?cc=" + emailCC + "&subject=" + emailSubject + "&body=" + emailBody;
};
I'm using a button at the end of my form to generate the email:
<input type="submit" value="Generate email" onclick="generateEmail()">
If you want to get the input value that the user typed you need to use :
$("#otherFreeTextField").val()
So you have to add a check if the other is checked then the reason will be the value of the input :
var reason = $(".reason:checked").val();
if( $('#otherRadioBtn').is(':checked') ) {
reason = $("#otherFreeTextField").val();
}
As a shortcut you could use :
$('#otherRadioBtn').is(':checked')?$("#otherFreeTextField").val():$(".reason:checked").val();
In you context the condition should be injected like :
function generateEmail() {
var emailTo = $("#teamName").val();
var emailCC = $("#CC").val();
var emailSubject = $("#ticketNumber").val();
var reason = $('#otherRadioBtn').is(':checked')?$("#otherFreeTextField").val():$(".reason:checked").val();
var emailBody = "Issue: " + $("#issue").val() + "%0A%0ACustomer Contact Information: " + $("#contactInformation").val() + "%0A%0ARequested Action: " + $(".requestedAction:checked").val() + "%0A%0AReason: " + reason + "%0A%0AWorkaround Available? " + $(".workaround:checked").val();
location.href = "mailto:" + emailTo + "?cc=" + emailCC + "&subject=" + emailSubject + "&body=" + emailBody;
};
This is happening because you are checking the status of textbox if visible or not.$(".reason:checked").val(). That's why it's giving on cause it's visible.
Try: $(‘.reason:textbox’).val()
I am trying to create a row of 3 form fields dynamically when the user clicks on the ADD button / plus symbol .
Javascript code used to create the form elements is below :
<script type="text/javascript">
var field_counter = 1;
var field_limit = 5;
species = document.getElementById('species');
breed = document.getElementById('breed');
function addInput(divName){
if (field_counter == field_limit) {
alert("You have reached the limit of adding " + field_counter + " inputs");
}
else {
var dynamic_species = 'species'+field_counter; //dynamic id for species
var dynamic_breed = 'breed'+field_counter; //dynamic id for breed
var dynamic_quantity = 'quantity'+field_counter; //dynammic id for quantity
var dynamicForm = '<div class="form-group"><div class="col-md-4"><label for="'+dynamic_species+'">Animal Type</label><select class="form-control input-sm '+dynamic_species+'" id="'+dynamic_species+'"><option></option></select></div>';
dynamicForm+='<div class="form-group"><div class="col-md-4"><label for="'+dynamic_breed+'">Breed</label><select class="form-control input-sm '+dynamic_breed+'" id="'+dynamic_breed+'"><option></option></select></div>';
dynamicForm+='<div class="form-group"><div class="col-md-2"><label for="'+dynamic_quantity+'">Quantity</label><input type="number" name="quantity_export" id="'+dynamic_quantity+'" class="form-control input-sm '+dynamic_quantity+'" /></div>';
var newdiv = document.createElement('div');
newdiv.innerHTML = dynamicForm;
document.getElementById(divName).appendChild(newdiv);
document.getElementById(dynamic_species).innerHTML = species.innerHTML;
document.getElementById(dynamic_breed).innerHTML = breed.innerHTML;
field_counter++;
}
}
</script>
<div class="col-md-2" >
<label for=""> </label>
<i onclick="addInput('dynamicInput');" style="cursor: pointer; border: none;" class="fa fa-plus form-control input-sm">Add</i>
</div>
Using the above code am creating the form fields "Animal Type , Breed and Quantity ", all together in a row as shown in the image . Maximum number of rows that can be added is limited to the value of the variable "field_limit".
The value of the drop downs are initially populated from the parent drop down using the code :
species = document.getElementById('species');
breed = document.getElementById('breed');
document.getElementById(dynamic_species).innerHTML = species.innerHTML;
document.getElementById(dynamic_breed).innerHTML = breed.innerHTML;
Question : How can I select the dynamically generated ID of the new form fields .
Here is the script am using to select the first row of form fields which is in the HTML when the page loads for the first time :
$("#species").change(function(){
$('#breed').empty();
//alert($(this).val());
var param = {'id':$(this).val()};
$.ajax({
type : 'POST',
url : '<?php echo base_url();?>select_breed',
dataType : 'json',
data: param,
success : function(data)
{
var select = $('#breed');
select.empty().append(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown)
{
alert(XMLHttpRequest.responseText);
}
});
});
The second row of form fields are created dynamically with the following ID's
First Field : Animal Type : ID="species1"
Second Field : Breed : ID="breed1"
Third Field : Quantity : ID="quantity1"
I am not able to select the dynamically generated form fields using the jquery selector :- eg: $("#species1").change(function(){}); , it is not working .
What I am trying to do ?
I need to get the value of these fields using its ID attribute. Any help would be highly appreciated . Thank you .
Use event delegation for dynamic generated content like so :
// change `document` to top level parent that existed on page or
// parent container
$(document).on("change", "#species1", function(){...});
Thats because they do not exists yet when binding to it's change event.
You could add the event listener in the add_input function, or use a more abstract event handler:
$("form").on("change", ".species", function () {
var id = $(this).attr("data-id");
...
});
This will require you to drop the ID's and use class attributes instead. Which is the way to go by my opinion.
You can attach the ID's using $(speciesElement).attr("data-id", id).
I have an empty form that needs to be filled with what I'd like to call mini-forms dynamically based on a condition. For example,this can be a form that asks for the names and locations of restaurants. Now, based on the number of restaurants(let's say 'm'), I'd like to add to the big form 'm' mini-forms that asks for the name and location. How can I use jQuery to create each of these mini-forms, that take in the name and the location of the restaurant and append them each to the big form. The html would look something like this. But I need to create this dynamically based on how many forms the user would need, and if he would need any.
Edit - I have learned that we cannot nest forms. I have renamed the inner 'form' elements to 'div'.
<form>
<div id = 1>
Name: <input type = "text" name = "name">
Location: <input type = "text" name ="location>
</div>
<div id = 2>
Name: <input type = "text" name = "name">
Location: <input type = "text" name ="location>
</div>
...
</form>
First you need to look for changes to the input where the user enters the number of restaurants:
$('#noofrestaurants').change(function(){
Then you need to loop through the number inputted and create new inputs each time:
var restaurants = $('#noofrestaurants').val();
for (var i = 0; i < restaurants; i++){
$('#miniformcontainer').append('<input type="text" name="rest_name[]"/><input type="text" name="rest_loc[]"/>');
}
});
You could try something like this:
<script>
function addMiniForms(n)
{
for (i=0; i<n ; i++)
{
var $div = $("<div id='" + i + "'></div>");
var $labelName = $("<label for='name" + i + "'>Name</label>");
var $inputName = $("<input type='text' id='name" + i +' />");
var $labelLocation = $("<label for='location" + i + "'>Location</label>");
var $inputLocation = $("<input type='text' id='location" + i +' />");
$div.append($labelName);
$div.append($inputName);
$div.append($labelLocation);
$div.append($inputLocation);
$("#containerid").append($div);
};
};
</script>
I have not tested this code, so it might need some tweaking.
You can't nest forms. If you want to have repeated inputs in a form, give them array-style names:
<div id = 1>
Name: <input type = "text" name = "name[]">
Location: <input type = "text" name ="location[]">
</div>
The back-end should convert these into arrays. For instance, PHP will fill in $_POST['name'] with an array of all the Name inputs.
The jQuery looks like:
divnum++;
$("form").append("<div id='"+divnum+"'>Name: <input type='text' name='name[]'">Location: <input type='text' name='location[]'></div>");
I've got two bits of code that I'd like to work together but I don't manage to integrate this jQuery snippet into the JavaScript correctly …
JavaScript:
(function(){
// Creates the plugin
tinymce.create('tinymce.plugins.mygallery', {
// Creates control instances based on the control's ID.
createControl : function(id, controlManager) {
if (id == 'mygallery_button') {
// Creates the button
var button = controlManager.createButton('mygallery_button', {
title : 'MyGallery Shortcode', // Title of the button
image : '../wp-includes/images/smilies/icon_mrgreen.gif', // Path to the button's image
onclick : function() {
// Triggers the thickbox
var width = jQuery(window).width(), H = jQuery(window).height(), W = ( 720 < width ) ? 720 : width;
W = W - 80;
H = H - 184;
tb_show( 'My Gallery Shortcode', '#TB_inline?width=' + W + '&height=' + H + '&inlineId=mygallery-form' );
}
});
return button;
}
return null;
}
});
// Registers the plugin
tinymce.PluginManager.add('mygallery', tinymce.plugins.mygallery);
// Executes this when the DOM is ready
jQuery(function(){
// Creates a form to be displayed everytime the button is clicked
var form = jQuery('<div id="mygallery-form"><table id="mygallery-table" class="form-table">\
<form id="myForm">\
<div id="input1" style="margin-bottom:4px;" class="clonedInput">\
Name: <input type="text" name="name1" id="name1" />\
</div>\
<div>\
<input type="button" id="btnAdd" value="add another name" />\
<input type="button" id="btnDel" value="remove name" />\
</div>\
</form>\
</div>');
[…]
});
})()
jQuery:
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
FYI: The JS creates a popup with a form (WordPress) and with the jQuery snippet I'd like to implement the feature that the user can add more input fields dynamically.
Thanks for your help!
You can put the jQuery snippet after your javascript code. That shouldn't be the problem since your jQuery code is merely binding events.
However, I can't tell where #btnAdd and #btnDel are. The problem may be that the elements are created after the jQuery code is run, hence when you called this:
$('#btnAdd').click(function(){...});
the element #btnAdd was not there.
Try this:
$(document).on('click', '#btnAdd', function(){...});
This will bind the click event to document (which is always present) instead of #btnAdd.
To improve the performance though, you should bind it to a parent of #btnAdd that you know for sure is present when document is ready.