JQuery can't get value of dynamically added fields - javascript

I have a hidden div with a simple form:
<div id="mb_clookup" style="display: none;">
<strong><font color="#0066CC">Search for existing customers</font></strong><br /><br />
<font color="#FFF">
Postcode: <input type="text" name="cl_zipcode" id="cl_zipcode" />
<span id="cl_search">Search</span>
</font>
</div>
This is displayed when the user clicks a button on the page. The user puts in the ZIP code, click on search and a JSON query is called. I have managed to make the Search button work with .live() but I cannot get the value of the input field. Here is the code:
$(document).ready(function(){
$(document).on( "click", "#cl_search", function() {
var pc = $('#cl_zipcode').val();
if(pc === '') {
alert('Please type in a post code first.');
}
else {
// JSON
}
});
});
Th pc variable comes up empty. I tried:$(this).find('#cl_zipcode').val() this comes up with undefined.
Please advise.

You can use the following
var pc= $("#mb_clookup").find('#cl_zipcode').val();
or
var pc= $("#mb_clookup :input").val();
check fiddle

With regard to $(this).find('#cl_zipcode').val() the input elements is beside the clicked span, so your find will search from the span on down (and it contains nothing aside from the text).
You need to move up the DOM first before you find it.
$(this).parent().find('#cl_zipcode').val()
Please note that as IDs are unique, so your original code is actually fine (so long as you only have one of these added): http://jsfiddle.net/TrueBlueAussie/djqfharu/
If you load more than one of these (you mention dynamic adding of fields) you will need to switch to classes to identify the elements.
e.g
$(document).ready(function(){
$(document).on( "click", ".cl_search", function() {
var pc = $(this).parent().find('.cl_zipcode').val()
if(pc === '') {
alert('Please type in a post code first.');
}
else {
// JSON
}
});
});
This is because browser keeps a fast-lookup dictionary, of IDs vs DOM elements, so only a single entry is retained per ID. The upshot of that is that jQuery can only ever find the first matching element for a search of a duplicated ID. The solution there is to switch to using classes and class-based searched.
I strongly suggest you post the rest of your code as the part shown is not the problem in isolation.

i thing your html code wrong. Becouse tag not in use tag
tag not support HTML5..
change this
<div id="mb_clookup" style="display:block;">
<strong><font color="#0066CC">Search for existing customers</font></strong><br /><br />
<span style="color="#FFF">
Postcode: <input type="text" name="cl_zipcode" id="cl_zipcode" />
<span id="cl_search">Search</span>
</span>
</div>
good luck

Your code is working fine i checked it in jsfiddle by removing display none attribute. You can check it here
HTML
<div id="mb_clookup">
<strong><font color="#0066CC">Search for existing customers</font></strong><br /><br />
<font color="#FFF">
Postcode: <input type="text" name="cl_zipcode" id="cl_zipcode" />
<button id="cl_search">Search</button>
</font>
</div>
JS
$(document).ready(function(){
$(document).on( "click", "#cl_search", function() {
var pc = $('#cl_zipcode').val();
if(pc === '') {
alert('Please type in a post code first.');
}
else {
alert(pc);
}
});
});

Related

JQuery Not Triggering On Button.click

I've written some code that should check a textbox (ID tfa_1) to see if its empty or contains text, this should trigger on a next page button (wfpagenextID6) being clicked.
I've tried replacing my script with an alert("test.") and it dosent appear, so im assuming I have my trigger wrong but I cannot work out what I have done wrong!
My HTML that defines the textbox is below:
<input type="text" id="tfa_2685" name="tfa_2685" value="" placeholder="" title="Previous Surname (if applicable) " class="">
and the button is
<input value="Next Page" type="button" class="wfPageNextButton" wfpageindex_activate="7" id="wfPageNextId6" style="visibility: visible;">
Both of these are generated and I cannot change them!
My Script is:
<script>
$(document).ready(function(){
$('#wfPageNextId6').click(function(){
var inp.Val= $("#tfa_2685").val();
if (inp.val().length > 0) {
alert("Test.");
}
});
})
</script>
An identifier ( variable ) must not contains dots. ( see more details ECMAScript specification in section 7.6 Identifier Names and Identifiers)
the next variable declaration is wrong
var inp.Val= $("#tfa_2685").val();
to fix this
var inp = $("#tfa_2685");
if you want to assign value to inp variable, you should just do: var inp = $("#tfa_2685").val();
And then call to inp.val() just replace with inp, for inp is not jQuery object so it doesn't have val() method
You have syntax, try this:
$(document).ready(function(){
$('#wfPageNextId6').click(function(){
var inpVal= $("#tfa_2685").val();
if (inpVal.length > 0) {
alert("Test.");
}
});
});
https://jsfiddle.net/cua40s80/

autocomplete on input field created with jquery after()

I have a field on which an autocomplete function is implemented. This is my code :
<%= f.text_field :auteur_1, size: 100, class:"champs_auteur", data: {autocomplete_source: auteurs_enum_path} %>
That creates the following html :
<input size="100" class="champs_auteur ui-autocomplete-input" data-autocomplete-source="/auteurs/enum" name="biblio[auteur_1]" id="biblio_auteur_1" autocomplete="off" type="text">
And this is in my javascript :
$(document).on('ready', function() {
return $('.champs_auteur').autocomplete({
source: $('.champs_auteur').data('autocomplete-source')
});
});
All that works fine. I am creating input fields using jquery after() and append(), like this :
$(document).on('ready', function () {
i = 2 ;
$(".extra_auteur").click(function(){
$('.premier_auteur').after('<div class="grid mbm"><div class="one-sixth"><label for="biblio_auteur">Auteur</label></div><input size="100" class="champs_auteur" data-autocomplete-source="/auteurs/enum" type="text" name="biblio[auteur_' + i++ + ']" id="biblio_auteur_1" /></div>');
});
});
This is minified code (mainly html) for :
<div class="grid mbm">
<div class="one-sixth">
<label for="biblio_auteur">Auteur</label>
</div>
<input size="100" class="champs_auteur" data-autocomplete-source="/auteurs/enum" type="text" name="biblio[auteur_' + i++ + ']" id="biblio_auteur_1" />
</div>
This does create the input field with an id="biblio_auteur_2" (and 3, 4 etc...).
The autocomplete doesn't work on the additional input fields. I don't see why not.
This is because you're using the element #ID instead of the class-name as in:
$( "#aut_extra" )
And #ID is always unique, and will therefore only work for 1 item. What yu need to do is have the jQuery select the CSS element class instead and not ID.
$( ".aut_extra" )
or whatever the class name is.
But you must be sure that the element which currently have the ID of aut_extra instead have a CSS class with the same name.
<div class="aut_extra"....
Crashtor is correct, page ids MUST be unique for proper functioning. However, you might have another issue. You're calling autocomplete during document ready, but when you change the dom by adding new fields, those existed after the autocomplete function was initialized.
Try calling autocomplete on each after append.
$('.extra_amatur:last').find('input[type=text]:last').autocomplete({
source: $(this).data('autocomplete-source')
});
Thanks both for your help. Both errors needed to be corrected, the first on that only classes should be used and the second that the autocomplete should be used on another event then document ready. I took on click.
This is the code (if this could ever help someone) :
$(document).on('click', '.champs_2_auteur', function() {
return $('.champs_2_auteur').autocomplete({
source: $('.champs_2_auteur').data('autocomplete-source')
});
});

How to set text box to appear blank after .click function

So I have a simple log in that requires a user to input values from a json file into two different text boxes ,when the user name and (in this case I have used ID as password) matches then an alert appears to say... "welcome"
After the .click function is carried out the users text still remains in the text box, how can I get both text boxes to appear blank after the .click function?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
for (var i=0; i<jd.user.length; i++) {
if ((jd.user[i].ID == id) && (jd.user[i].name == name)) {
valid=true;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
//console.log('here');
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
}
});
}); });
username 1 and #username 2 are the text boxes - is there any way to get user name 2 to display in stars ****** when the user enters the password - this question is not that necessary but if i could also get that working that would be good.
thanks guys hope someone can help :)
is there any way to get user name 2 to display in stars ****** when
the user enters the password
You can use an input box with text property set as password. But that password masking character will be . instead of *. Not exactly sure, whether it will be a different character in some browsers.
<input type="password" id="txtPassword" />
text box to appear blank after .click function
You can set the .val() property of the jQuery objects of two those two textboxes.
$('#userName, #username2').val('');
Use <input type="password"> to show typing as stars.
Clear inputs by setting their value to be empty: $('#userName').val('');
And perhaps consider breaking your code down into a couple smaller functions so it's easier to follow.
document.getElementById("#myTextbox").value="";
This should get your textbox and set the value of it to "", which is blank.
Edit: JSFiddle
Another Method:
You can also add the script directly inside the button without using/creating a function.
<input id="inputId" type="name" />
<button onclick="document.querySelector('#inputId').value='';"> Clear </button>
Using querySelector:
<input id="inputId" type="name" />
<button onclick="click()"> Clear </button>
<script>
function click() {
document.querySelector('#inputId').value="";
}
</script>

How can i refer to a span element in a form?

I have a question with SPAN elements in a FORM in javascript.
I'm studying 'form & validation' w/headfirst js book and
there are some examples like below,:
-.html
<form name="orderform" ...>
...
<input id="zipcode" type="text" name="zipcode" onblur="validateZipcode(this, document.getElementById('zipcode_help'));" />
<span id="zipcode_help"></span>
....
<input type="button" name="submit" onclick="placeOrder(this.form);" />
</form>
-.script
function validateZipcode(inputField, helpText) {
....
helpText.innerHTML = "Please enter a number";
....
}
function placeOrder(form) {
...
if (validateZipcode(form["zipcode"], form["zipcode_help"]) {
form.submit();
....
}
and here is my question.(It's not the same as the title I wrote, btw.:/)
How can a span element, be referred as "form["zipcode_help"] in the function placeOrder?
I know all form fields can be referred with its "name" property.
and I thought a span element can't be like that because it doesn't belong to a form and haven't even got a name property.
I now have changed my question slightly.: How " document.getElementById("zipcode_help")" can be equal to "form["zipcode_help"]? The THING which is found by getElementById method is a SPAN, not a FORM FIELD. And, "zipcode_help" in "form[]" is an ID, not a NAME property, so it seems to me that it's even WRONG in grammar!
Your span has an id, so use the document.getElementById() method:
if (validateZipcode(form["zipcode"], document.getElementById("zipcode_help")))
And remember that (unlike form element names) id has to be unique.
EDIT: I just noticed that you already do what I've shown above in your onblur= handler, so apparently I'm not telling you anything you didn't already know.
For the html that you show, where the field and its associated help span have related ids, you may like to consider something like this:
function validateZipcode(inputField) {
var help = document.getElementById(inputField.id + "_help");
if (inputField.value === "") {
help.innerHTML = "Please enter a number";
return false;
}
help.innerHTML = "";
return true;
}
function placeOrder(form) {
if (validateZipcode(form["zipcode"])){
alert("Submit");
}
}
That is, just pass the field itself to the function, and then figure out from its id what the associated help field will be.
Demo: http://jsfiddle.net/kY3BJ/

Replace input value .val() with jQuery

So basically here is my jsFiddle - http://jsfiddle.net/CmNFu/ .
And code also here -
HTML -
<b style="float: left; margin-right: 10px;">category 1</b><input type="checkbox" value="category1" style="float: left;" class="portfolio-category" /><br />
<b style="float: left; margin-right: 10px;">category 2</b><input type="checkbox" value="category2" style="float: left;" class="portfolio-category" /><br />
<br />
<br />
<input type="text" name="categories" id="portfolio-categories" />​
jQuery -
jQuery(document).ready(function() {
jQuery(".portfolio-category").click(function() {
if(jQuery(this).is(":checked")) {
jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+" "+jQuery(this).val());
}
else {
var portfolioCategories = jQuery("#portfolio-categories").val();
alert("before + "+portfolioCategories);
var currentElement = jQuery(this).val()+" ";
alert(currentElement);
portfolioCategories = portfolioCategories.replace(currentElement, "");
alert(portfolioCategories);
}
});
});
​Well basically what I would like to achieve is, when user checks the checkbox, the value automatically adds inside input field (Done, it's working, whooray!), but the problem is when it unchecks the checkbox, the value should be removed from input box (the problem starts here), it doesn't remove anything. You can see I tried assigning val() function to variables, but also without success. Check my example on jsFiddle to see it live.
Any suggestions? I guess replace() is not working for val(), is it?
So, is there any other suggestions?
I'd do this:
jQuery(document).ready(function() {
jQuery(".portfolio-category").on('change', function() {
var string = "";
$('input[type="checkbox"]').each(function() {
var space = string.length>0?' ':'';
string += this.checked?space+this.value:'';
});
$("#portfolio-categories").val(string);
});
});
FIDDLE
You have quite the issue with spaces in that input box. but we'll get to that in a moment.
first, this will kind of work (if it weren't for the spaces problem):
add this line before the last alert:
jQuery("#portfolio-categories").val(portfolioCategories);
this will work, but not always, as the last element you append doesn't have a space after it.
but if you change the 4th line to this:
jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+jQuery(this).val()+" ");
it will work, as it adds the space after each element, instead of before.
http://jsfiddle.net/CmNFu/5/
your issue was that you changed the values in the variable: portfolioCategories, but you haven't updated the input itself. (notice, changing the value of a string, doesn't change the value of the input it originally came from)
What you need is to insert back the string portfolioCategories into the input. Also the spaces are creating a lot of problems. You could use $.trim(str) to remove any leading and trailing spaces from a string.
Have updated your fiddle with a solution that works.
http://jsfiddle.net/CmNFu/11/
Hope this helps.

Categories