I cant pick the value of input using jquery - javascript

$('.submit__form').on('click', function(e) {
e.preventDefault();
var id = '.' + $(this).data('id');
var person__name = $('#person__name').val();
var person__email = $('#person__email').val();
var booking__participants = $('#booking__participants').val();
alert(person__email || 'none');
// if (person__email === '' || person__name === '' || booking__participants === '') {
// alert('Preencha os campos obrigatórios.');
// } else {
// $(id).submit();
// }
});
I don't know why, but i can't pick the value of the person__name and person__email, the most strange part is that i can pick the value in the console on the browser... someone knows what could be causing this?
This is not a problem of html the 2 inputs fields have the id person__name and person__email.
The code is in a external file, and i am calling that in the bottom of my html.
HTML:
<form>
<input id="person__name" name="person.name" type="text" />
<input id="person__email" name="person.email" type="email" />
<a class="submit__form">Submit</a>
</form>
I cant use the submit input.
UPDATE:
The scripts in the bottom of the page:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.mask/0.9.0/jquery.mask.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/headroom/0.6.0/headroom.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/waypoints/2.0.5/waypoints.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/velocity/1.1.0/velocity.min.js"></script>
<script src="//cdn.jsdelivr.net/velocity/1.1.0/velocity.ui.min.js"></script>
<script src="/client/scripts/main.js"></script>
Inside the main script:
(function() {
//code
})();

If you want to alert the name, make sure you use the name in the jQuery
alert(person__name || 'none');
// Not:
alert(person__email || 'none');
http://jsfiddle.net/376fLujs/3/
Also, make sure your script is included properly. Include the jQuery before your script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="local.js" type="text/javascript"></script>
add: console.log("working"); as the very first line of your script
open the chrome console / Firebug and refresh your page.
if you don't see "working" in the console, your javascript is not included properly.
Edit: based on your comments again. If you have multiple forms, re-using the same ID, it will not work. Always keep IDs unique. Since your link is inside of the form like your input, you could do this:
var person__email = $(this).parent().find("input[name='person.email']").val();
// DRX points out that escaping may be necessary:
var person__name = $(this).parent().find("input[name='person\\.name']").val();
http://jsfiddle.net/376fLujs/4/

I would say try using this for your event handling:
$(document).on('click', '.submit__form', function(e) {
//code here
});
The reason it might not be working is because the element might not yet be created when the script loads. This should take care of that issue.

Related

Validate a SELECT against another SELECT PHP JQuery

Within my form there are 2 SELECT Options. I'm looking to check the values of both, to check that they match.
This below is my jquery, when the code runs, I deliberatly have different values in the SELECT options and the form will just carry onto the next page without flagging up the error that they don't match.
<script type="text/javascript">
$(document).ready(function () {
jquery(function(){
$("leadgenform2").click(function(){
$(".error").hide();
var hasError = false;
var exppagesval = $("#exppages").val();
var pagesseenval = $("#pagesseen").val();
if (exppagesval != pagesseenval) {
$("#pagesseen").after('<div class="alert alert-success display-hide"><button class="close" data-close="alert"></button>Pages Seen & Expected Pages do not match!</div>');
hasError = true;
}
if(hasError == true) {return false;}
});
});
});
</script>
What have I missed?
Not sure why formatting has gone a miss. sorry!
hey $("leadgenform2") is invalid selector either make it a class or id(preferred) and use like
$(".leadgenform2") for class.
$("#leadgenform2") for id.
$("leadgenform2") is not a valid selector. assuming it is an ID, so you should use $("#leadgenform2").
Just from a first glance... you seem to have an error on line1:
jquey(function(){
should be
jquery(function(){
And you are missing $(document).ready(function(){ .... );
Without this, click event will not fire.

Re-run javascript code when the value changes

I have two files: a html file (with the code below) and a javascript file (it creates a value for the <span id="quantity">) The code works fine, but the word only changes if I refresh the whole page.
I want the word to change from 'articles' to 'article' or vice versa as soon as the 'quantity' changes. Is this possible? And if so, how?
<span id="quantity" class="simpleCart_quantity"></span>
<span id="quantityText"></span>
<script type="text/javascript">
$(window).load(function()
{
var quantity = document.getElementById("quantity"),
quantityText = document.getElementById("quantityText");
if (parseInt(quantity.innerHTML, 10) === 1) {
quantityText.innerHTML = "article";
} else {
quantityText.innerHTML = "articles";
}
});
</script>
You might want to look into MVVC framework like Knockout JS. For example, you would set the contents of the #quantity <span></span> element to be an observable.
However, try reading this SO thread to find a solution similar to what you probably are hoping for. In summary, change events only occur from the browser on the blurring of form fields, so you'll need to implement a $("#quantity").trigger('change')
Once you have a trigger set-up after the DOM element has been loaded, you can do the following:
$('#myParentNode').on('change','#mynum', function() {
// Add your logic in here
$('#quantityText').text('articles') .... .. .. .....
});
Normally, the span element doesn't fire a change event, so you cannot subscribe to it, like you would normally do in an input element.
However, you can trigger such an event using jQuery in the same code, which changes the value of the span (I assume there is such code, because normally spans don't change value).
Here is an example which simulates this change every 10 seconds, and triggers the change event. It also includes a handler for that change event, which duplicates the value in the other span.
<span id="quantity" class="simpleCart_quantity">1</span>
<span id="quantityText"></span>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var quantity = $("#quantity"),
quantityText = $("#quantityText");
setInterval(function() {
var currentVal = parseInt(quantity.html());
if (currentVal >= 10) {
quantity.html(1);
}
else {
quantity.html(currentVal + 1);
}
quantity.trigger('change');
}, 10000);
quantity.on('change', function(sender, args) {
quantityText.html($(this).html());
});
});
</script>

HTML error cannot set property of null (anonymous function)

I'm trying to store a textbox value to local storage however I'm catching an Uncaught TypeError: Cannot set property 'onclick' of null and not sure exactly why. Everything seems to be referenced correctly. Any insight would be appreciated.
<script type="text/javascript">
var save_button = document.getElementById('Save')
save_button.onclick = saveData;
function saveData()
{
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.value);
var storedValue = localStorage.getItem("server");
};
</script>
<label for="serveri">Server:</label>
<input type='text' name="server" id="saveServer" />
<button onclick="saveData()" type="button" value="Save" id="Save">Save</button>
If the above doesn't show my problem, here is the whole in JSFiddle: http://jsfiddle.net/mGfeu/
Write the script after the body. The DOM isn't loaded when your script executes. Hence there is no element with id 'Save'.
Your code is run before the DOM is ready (so the .getElementById cannot find your element)
Change your code to
// attach events for all browsers
var prefix = window.addEventListener ? "" : "on";
var eventName = window.addEventListener ? "addEventListener" : "attachEvent";
document[eventName](prefix + "load", init, false);
function init() {
var save_button = document.getElementById('Save');
save_button.onclick = saveData;
}
function saveData() {
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.value);
var storedValue = localStorage.getItem("server");
alert(storedValue);
}
You are looking for the element before it is rendered on the page.
Your fiddle is messed up since you included the script block in the HTML markup and in the JavaScript panel. The one in the HTML markup is firing the error since it is not running at onload or document ready.
Your fiddle works if you take out the script (you just need to include the html from the body) and put it in the js area only, because that is using an onload script to render:
http://jsfiddle.net/spacebean/mGfeu/1/
It's returning the localStorage element correctly and everything is being set fine.
For your code just make sure to wrap it in an onload event, e.g.:
<script type="text/javascript">
//<![CDATA[
window.onload=function(){ /* your js here */ }
//]]>

get the href value by clicking on anchor in multiple anchors using jquery

i'm trying to get the href value in multiple links or tag a.and i tried with this code
var val;
$(document).ready(function() {
$("a").click(function() {
window.val = $(this).attr("href");
alert(window.val);
});
it is working fine for the multiple links and which is inside the file that is local, here few demo links
a
b.....
but problem is i want that href value globally available because i'm using that in other file . My problem is how to make it global, or is there any other way to do it.
and how to write our own function to work the same thing without using $(document).ready function.
this whole thing in one html page but i want only href value in other html page , so if we write our own js function we can use this in both html pages . And that function should return href. but here i dono how to return to $(document).ready function.
You can create an object-based variable:
var screen = {
link:''
};
And then assign / access on click:
$('a').on('click',function(){
screen.link = this.href;
alert(screen.link);
});
I advocate this over assigning variables to the window ... a little more control this way.
Notice I used this.href instead of $(this).attr('href'). As the most interesting man in the world says, I don't always use vanilla JS, but when I do it's about 600,000 times faster.
EDIT So you want to get rid of $(document).ready() huh? Now you're venturing into the shark-infested waters of pure vanilla JS.
var screen = {
link:'',
assignLink:function(href){
screen.link = href;
alert(href);
}
},
links = document.getElementsByTagName('a');
if(window.addEventListener){
for(i = links.length; i--;){
links[i].addEventListener('click',function(){
screen.assignLink(this.href);
});
}
} else {
for(i - links.length; i--;){
links[i].attachEvent('onclick',function(){
screen.assignLink(this.href);
});
}
}
This is just winging it, so don't scathe me if it isn't flawless, its more to make a point. See why jQuery is so handy? All that extra crap is done in the background for you, so that you just need to deal with the burden of $(document).ready() and not have to deal with the rest of this kind of stuff.
EDIT AGAIN So ... you want to access this value across pages?
var screen = {
link:((localStorage['link'] !== null) ? localSorage['link'] : ''),
setLink:function(href){
screen.link = href;
localStorage['link'] = href;
alert(href);
},
getLink:function(){
return screen.link;
}
};
$('a').on('click',function(){
screen.setLink(this.href);
});
This use of localStorage is just an example ... you can get more elaborate or use cookies if you want IE7- to work, but this just providing ideas. You can set the value whenever you want using the screen.setLink function passing the href, or you can get the value whenever you want using the screen.getLink function.
Take a look at this example:
<!DOCTYPE html>
<html>
<head>
<title>Try jQuery 1.9.1 Online</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var val;
$(document).ready(function() {
$("a").on('click', function() {
window.val = $(this).attr("href");
alert(window.val);
return false;
});
$("div").on('click', function() {
alert (val);
});
});
</script>
</head>
<body>
a
b
<div>click here</div>
</body>
</html>
Once you click either the link a or b val will be set. Clicking the div tag will alert you the current reference of val.
Declare val outside to make it global and you can use the val inside the function to set the href globally
var val;
$(document).ready(function() {
$("a").click(function(e) {
e.preventDefault();
val = $(this).attr("href");
alert(val);
});
});
jsfiddle

Best way to modify an element that is not yet created

I have an <input> field in my web page, and I want to add a particular method on it, let say fooBar().
Here is what I do:
<input id="xxx" .../>
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
This works well. However, for some reasons I will not detail here (in fact the HTML is generated by JSF components), the <script> will be declared before the <input> tag.
So in others words, I will have that in my HTML:
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
<input id="xxx" .../>
So of course this code will not work correctly, as the script will try to get ($("xxx")) and modify an element that does not exist yet.
If I want to stick on the exact order of these two tags, what is the best way to accomplish what I want?
Edit
In my case, $ refers to prototype, but I am also using jQuery in my application. And I must be compatible with IE6 :o(
You need to run your script after the document is loaded. With jQuery you'd do that with:
$(document).ready(function () {
//do stuff here
});
I can't tell which library you're using here, but they all have an equivalent of jQuery's document ready.
Here's the prototype equivalent:
document.observe("dom:loaded", function() {
// do stuff
});
Try putting your code in load event:
$(window).load(function(){
$("#xxx").fooBar = function() { ... };
});
If the code has to be directly before the input, you can check if it has loaded after a certain period of time.
<script type="text/javascript">
//Sets up a function to execute once the input is loaded
f = function ()
{
//Checks if 'xxx' exists (may vary between frameworks)
if ($("xxx") !== undefined)
{
$("xxx").fooBar = function() { ... };
//Escapes the timer function, preventing it from running again
return true;
}
//If still not loaded check again in half a second (0.5s or 500ms)
setTimeout(f,500);
return false;
}
f();//Initialize the timer function
</script>
<input id="xxx" .../>
Instead of adding a method to the dom node, why not make it a separate function, so instead of
$("xxx").fooBar = function() {
doStuff(this);
};
you would have something like
function xxx_fooBar () {
var me = document.getElementById('xxx');
doStuff(me);
};
Another suggestion: If you can add attributes to the <input> element, you could do something like this...
<script>
function xxx_init (e) {
e.fooBar = function () {
doStuff(this);
};
}
</script>
<input onload="xxx_init(this)" id="xxx" .../>
Or you could do as others suggest and attach the scripts to the window.onload event.

Categories