I am trying to simply get the value of an input, and attach it to a 'zipcode' variable. However whenever I try to console the value, it just comes up as blank.
$(document).ready(function(){
var zipcode = $('.zipcode-search').val()
$('#button').on('click', function(){
console.log(zipcode)
})
HTML
<div class="col-sm-12">
<div class="text-center">
<input class="text-center zipcode-search" type="text" name="zipcode-search" placeholder="Enter your city"/>
<button id="button" class="btn btn-success">
Submit
</button>
I am doing this on codepen.io. I'm not sure if that would have anything to do with it but I thought I might add that. Is there any other way besides .val() to get the value of an element ?
.zipcode-search, doesn't have a value when the page loads, and your variable's value is only assigned once, when the page loads.
If you want to update your variable whenever your button is clicked, you'll need to move your call to $.val, into your click event handler.
Here's an example:
$(document).ready(function() {
var zipcode = null;
$('#button').on('click', function() {
zipcode = $(".zipcode-search").val();
console.log(zipcode);
});
});
Note how I assign zipcode a value of null when the page loads, I did this because the chances of .zipcode-search having a value when the page loads, are slim-to-none without more advanced logic.
Edit: Examples provided in other answers, have been redeclaring the zipcode variable every time your button's click event is fired. This is not needed.
Declaring/redeclaring the variable every time the click event is fired, makes that variable exclusive to the scope of your callback function for the click event, which will prevent you from being able to reuse the variable outside of that callback.
I'm assuming you want to update zipcode everytime the button is clicked. You should move that logic to be inside of your event handler.
$(document).ready(function(){
$('#button').on('click', function(){
var zipcode = $('.zipcode-search').val()
console.log(zipcode)
})
You should get the value inside the onClick function:
$(document).ready(function(){
$('#button').on('click', function(){
var zipcode = $('.zipcode-search').val()
console.log(zipcode)
});
});
Related
Hello stackoverflow: I am working on getting a click event save into local storage. However, I get that it is undefined as the answer. This is what I have so far as my click event:
$(document).ready(function() {
$(".btnlocalStorage").on("click", function() {
event.preventDefault();
console.log("I am clicked!")
var myContent = $(this).(".btnlocalStorage").val();
localStorage.setItem("myContent", myContent);
//localStorage.setItem("myContent", JSON.stringify(myContent));
})
})
This is the HTML part of it, a button and a text area:
<textarea type="text" class="TextBoxColors-17 form-control" id="TextBoxStorage-17" aria-label="5:00 PM" aria-describedby="inputGroup-sizing-sm"></textarea>
<button class="btn btn-primary btnlocalStorage" type="button" todo="saveToDo-11am"><i class="fa fa-floppy-o" style="font-size:18px;"></i>
</button>
What should happen is that when I type any content into the text area, when I click the save button, this content should be saved into local storage. I am getting the key name, but the value/content undefined. Please, help me get this working. Thanks!
You're trying to get the value of your button instead of the value of the textarea with:
$(this)
Your code should look like this :
$(document).ready(function(){
$(".btnlocalStorage").on("click", function() {
localStorage.setItem("myContent", $(".TextBoxColors-17").val());
console.log(localStorage.getItem("myContent"));
})
});
EDIT :
This code only works for one specific textarea, if you want to make it work for multiple textareas followed by a button, you must use :
$(this).prev()
"this" refers to the button wich triggered the event and the prev() function allow you to get the element just before it.
Be careful, your local storage item must have a different name from one button to another, otherwise all buttons will override the same item content, for the example I took the ID of your textarea but it can be any iterated variable :
$(document).ready(function(){
$(".btnlocalStorage").on("click", function() {
localStorage.setItem($(this).prop("id"), $(this).prev().val());
console.log(localStorage.getItem($(this).prop("id")));
})
});
It works this way: when I click a subscribe button, it shows a message:
<span id="es_msg">
Your subscription was successful! Kindly check your mailbox and confirm your subscription. If you don't see the email within a few minutes, check the spam/junk folder.</span>
And I have to change this message using javascript cause I don't have access to the html. I tried to use the code below, but the message "Test" becomes always visible even before I click the subscribe button.
document.getElementById('es_widget_msg').innerHTML='Test';
That's because you didn't set the code up to be part of an "event handler". It's running without any user involvement, as soon as it's encountered. You said yourself you want the text to change when the span gets clicked.
// Get a reference to the span
let span = document.getElementById("es_msg");
// Set up a click event that references the correct event handling function
span.addEventListener("click", doClick);
// Define the handler function
function doClick(){
// In the DOM handler, the element that caused the event
// is available via the keyword "this". Also, if you are not
// modifying the HTML content of an element, use .textContent
// not .innerHTML
this.textContent = 'Test';
}
<span id="es_msg">
Your subscription was successful! Kindly check your mailbox and confirm your subscription. If you don't see the email within a few minutes, check the spam/junk folder.</span>
You can store the msg inside the data-* attribute of an element.
var $el_btn = $("#es_txt_button");
var $el_msg = $("#es_msg");
$el_btn.on("click", function(e) {
e.preventDefault();
// submit to backend and on succes do:
$el_msg.text($el_msg.data("msg"));
})
<button id="es_txt_button">Subscribe</button>
<span id="es_msg" data-msg="Your subscription was successful!"></span>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
or in plain JS
const el_btn = document.querySelector("#es_txt_button");
const el_msg = document.querySelector("#es_msg");
const subscribe = (e) => {
e.preventDefault();
// submit to backend and on succes do:
el_msg.textContent = el_msg.getAttribute("data-msg");
};
el_btn.addEventListener("click", subscribe);
<button id="es_txt_button">Subscribe</button>
<span id="es_msg" data-msg="Your subscription was successful!"></span>
You try below jQuery code..
$('body').on('click', '#subscribeId', function() {
$('body').find('#es_msg').text('Test');
});
If you do not use a event handling machanisum in doing this the code you have add will work on page load and rewrite the message as 'Test' very early than you expecting. So that, you have to add handler. Here we handle the click on the subscribe button with the subscribe button Id or the class name. In this case the action will take place only if the event happens, ie. Your click on button.
Hope this helps you.
Okay, so I have a button inside a div. Here is that bit of HTML:
<div class="row">
<button type="button" id="submit">Send</button>
</div>
Before this button, there are other fields like name and email and stuff, and those are all inside a form, with the id "contactForm" (which is inside a div with class name "container").
I am making a JS file. I am trying to get it so that when the user puts in all the info like name & stuff, and hits submit, it will console.log() the name. That JS portion looks like this:
// Listen for submit btn click
document.getElementById('contactForm').addEventListener('submit', submitForm);
function submitForm(e) {
e.preventDefault();
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var message = document.getElementById('message').value;
console.log(name);
};
Right, so this part looks fine to me, but then when I go into the localhost where the website is, and i put in whatever random stuff into the name, email and message fields, and i hit submit, nothing happens.
The debugger/console says
Uncaught TypeError: Cannot read property 'addEventListener' of null
On line 48, which is this:
document.getElementById('contactForm').addEventListener('submit', submitForm);
I started learning js today, so pretty new, but i cant find anything online that solves this problem. I found some that suggested i put the big JS portion inside a document.ready function, so it runs after everythings loaded. If I do that, which I tried, there is no error (like the line 48 one). It just doesnt say anything, and clicking on the btn doesnt do anything either (as in, doesnt show the name like i wanted).
Pls help, thanks.
If you want to use the "Submit" event, you have to made a form which have <input type="submit">, your button with the id'submit' is not a valid submit button.
For simple, if you want the function to be executed when your button is clicked, just use this:
document.getElementById('submit').addEventListener("click", function(){
e.preventDefault();
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var message = document.getElementById('message').value;
console.log(name);
});
You may be trying to attach an event even before the DOM has been loaded. You could use multiple solution for this.
Place your javascript code after the tag.
<form id='contactForm'></form>
<script>**** All your JavaScript goes here **** </script>
Place your code inside DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('contactForm').addEventListener('submit', submitForm);
});
have you checked your form's id for misspelling ?
also you can change a submit button to a simple div and add an onclick event handler instead if preventing default behavior. use it like this :
document.getElementById('submit').onclick=function(){document.getElementById('my-test-p').innerHTML='Submit was clicked'}
<button type="button" id="submit">Send</button>
<p id='my-test-p'></p>
I have set up a page with a form that users can make changes to using PHP. When they try to navigate away from the page or refresh, an alert box appears using JS. However when they click the Save button the alert box still appears.
Is there any way I can stop the alert box appearing when the user clicks on the save button?
here is my JS:
var needToConfirm = true;
$('#save').click(function(){
var needToConfirm = false;
})
if (needToConfirm == true)
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Here is my HTML (just the button): -->
<input type="submit" id="save" />
<input type="hidden" id="save" name="submitted" value="TRUE" />
If I understand correctly, you don't want to show the confirmation dialog when someone clicks the save button right? Why not just deregister the onbeforeunload method in that click handler like so:
window.onbeforeunload = confirmExit; //By default assign the confirmExit
//If user clicks on save, just set it to null.
$('#save').click function(){
window.onbeforeunload = null;
}
This way, you don't need to maintain a separate variable called needToConfirm. Also, try to understand the way javascript executes your code. It does it line by line. So, your needToConfirm defined inside the click handler right now gets set to false when the user clicks save. But even before that callback is called, you already have bound the onbeforeunload event as the default value of needToConfirm is true.
Try to also keep in mind the scoping of variables in javascript. If you redefine variable needToConfirm inside a click handler it would not necessarily access the "global" variable you intend to share across different functions. And ofcourse, like other people pointed out, don't use the same id for different HTML elements. It is not supposed to be used like that.
First of all, you are not executing your conditional code inside the if statement. It is out of it, fix that and try again. If it still doesn't work then try the following:
The page get refreshed before the $("#save").click() returns anything (in this case, needToConfirm = false. Therefore the alert box appears as usual. You have to modify your html as follows:
<input type="button" id="save" />
and use javascript to actually submit the form... You can do that as follows:
$("#save").click(function() {
var needToConfirm = false;
$("#idOfForm").submit();
return false;
}
Also, change ID of one of the buttons as 2 elements can never have the same ID... or use class instead!
In a form, i have a button and an image... when i click on image, form action is called, that work... but when i click on the button action is not called.
Is there a specific thing to do for a button?
js
$('#formUser').submit(function() {
$(this).attr("action", "/secure/downloaduserinfo/" + reportName);
});
$('#formUser').submit(function() {
$(this).attr("action", "/secure/deleteuser/" + reportName);
});
web part
<button type="button" id="deleteUserButton${statusReport.count}"></button>
<input id="downloadUserButton${statusReport.count}" type="image"/>
type="button" elements are not submit buttons, they exist solely to run client side code.
If you want to submit the form, use type="submit" (or don't specify a type attribute at all, submit is the default).
That said, I'd avoid the dependancy on JavaScript. Give the buttons and name and a value and use that on the server to determine if you want to download or delete.
The input of type "image" is similar to "submit", it does submit your form, that's why your submit handler is working. While the input of type "button" does not submit the form, it just looks like a button.
You have 2 submit listeners for the same element so every time the #formUser is submitted it uses the first submit listener it finds.
You can use the onclick listener and tie it to the specific element being clicked.
I'm not sure how the templating system it looks like you're using is tied in but I'd use a class instead of the id.
<button type="button" class="delete-user-button" id="deleteUserButton99">Delete</button>
<img src="http://placehold.it/200x200" class="download-user-button" id="downloadUserButton99"/>
<script>
$('.delete-user-button').click(function() {
// store object that was clicked
var obj = $(this);
// set that objects action attribute
obj.attr("action", "/secure/deleteuser/" + obj.attr('id'));
// show the action attribute's value
alert(obj.attr('action'));
});
$('.download-user-button').click(function() {
// store object that was clicked
var obj = $(this);
// set that objects action attribute
obj.attr("action", "/secure/downloaduserinfo/" + obj.attr('id'));
// show the action attribute's value
alert(obj.attr('action'));
});
</script>
Here's a fiddle that demonstrates manipulating the object by the click listener: http://jsfiddle.net/chapmanc/HHfQT/2/