Button not opening another HTML file after clicking check box - javascript

I have been trying to get my Terms and Service conditions HTML page to have a checkbox with a button that opens the next page (another HTML page) only if check box is checked. When I check the check box the continue button doesn't load next page. Even if the checkbox is unchecked it does not load the next page.
<h2>Terms and Service</h2>
<div class="ex3">
My conditions and terms.................................
</div>
<script>
document.querySelector('.checkbox').checked
</script>
<form>
<input type="checkbox" class="checkbox" required>I agree to all Terms and Conditions</br>
</form>
<button onclick="other_page.html">Click</button>
Thanks for helping me out!

There are a couple of reasons why this code isn't working.
Firstly, the onclick handler doesn't work like that. It executes JavaScript code within it, so you could just redirect with a simple
<button onclick="window.location='other_page.html'">Click</button>
but you need it to be conditional. So you would call a JavaScript function to do that.
var redirectIfClicked = function () {
// check if the checkbox is checked
var isChecked = document.querySelector('.checkbox').checked
// If it is then we can redirect using window.location
if (isChecked) {
window.location = 'other_page.html'
} else {
// it isnt checked so don't do anything (or do something else)
console.log('Dont do anything')
}
}
<h2>Terms and Service</h2>
<div class="ex3">
My conditions and terms.................................
</div>
<form>
<input type="checkbox" class="checkbox" required />I agree to all Terms and Conditions
</form>
<button onclick="redirectIfClicked()">Click</button>
The code above is ran when the button is clicked. It first checks if the checkbox is checked. If it is, then it redirects to your chosen page. If it isn't then it does nothing.
Secondly, this does nothing:
<script>
document.querySelector('.checkbox').checked
</script>
This returns true or false, so your code effectively becomes
<script>
true
</script>
You aren't doing anything with this and it wouldn't work even if you did because you aren't waiting for the DOM to be loaded.

Related

Stop double-clicking of submit button with Javascript

Here's my situation. I have a submit button. When clicked, some backend/database validation takes place and if everything's good, submit the form and disable the button so the form can't be submitted twice. If it does not pass validation, submittal cannot take place and the button stays active, so the user can resubmit the form. It sounds simple but I can't make it work. This is a C# web application.
I have tried to add the code to the button on page load. When the submit button is clicked and if validation fails, remove the code that disables the button. But here is my problem. Since the "disable" code is removed and the user fixes any error and resubmit, the button can be clicked more than one as the code is no longer there.
I do not want to use Ajax for this because the backend check is very complicated. Is there another way to do it? I've tried to add the "disable" code on "load" but it does not work on post back when the validation fails.
if (window.addEventListener)
window.addEventListener("load", lockSubmit, false);
else if (window.attachEvent)
window.attachEvent("onload", lockSubmit);
else window.onload = lockSubmit;
Any help is appreciated.
Try the snippet below
window.onload = function(){
// Insert the following function somewhere in your .js file / section
(function prevent_over_submitting(){
var form = document.forms.theform;
if(form || form.nodeName == 'FORM'){
form.onsubmit = function(){
form.submit.value = 'Proccesing...';
form.submit.disabled = true;
};
}
})();
};
While your form should look something like this one
<form id="theform" method="post" action="">
<input type="text" name="firsname" value="" />
<input type="text" name="lastname" value="" />
<input type="submit" name="submit" value="submit" />
</form>
Here is a working jsBin so you can play around.
Update:
The logic behind the snippet above
// server-side code (rather in pseudo-code this time)
if(form_has_been_submitted){ // check if the form has been submitted
errors[] = validate_data(post_data); // call the method to validate data
if(errors_array_is_empty){ // if everything is fine
submit_data(); // submit data
redirect_or_do_something; // (maybe) do other things
} // otherwise don't do anything
}
// validation method
validate_data(post){ // the only argument here represents all your form data
error = array;
if(post['firstname'] == wrong){ // check for error
error['firstname'] = 'Check your firsname'; // if you found one, push it to the error array
}
if(post['lastname'] == wrong){ // the same as in previous case
error['lastname'] = 'Check your lastname'; // the same as in previous case
}
return error; // return that array, it might be full or empty
}
// client-side code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyApplication</title>
<script type="text/javascript">
// the JavaScript snippet from above
</script>
</head>
<body>
<form id="theform" method="post" action="">
<input type="text" name="firsname" value="" />
<!-- show the error if you found one, otherwise show an empty string -->
<span><% (error['firstname'] ? error['firstname'] : "") %></span>
<input type="text" name="lastname" value="" />
<!-- same as in the previous case -->
<span><% (error['lastname'] ? error['lastname'] : "") %></span>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
As you can see, the JavaScript snippet above only disables the submit button onclick to prevent over-submitting; it will be enabled once the page is loaded again. This isn't my favorite way of validation but I followed your logic.
you can add this code in the onclick function:
First, add a global javascript variable, say var click = false;
and add this condition before validation occurs:
if(click){
return false
} else {
your normal validation code
}
if your page reloads each time you submit, then there is no need to add anything further, but if doesn't then add setInterval method which will reset the click variable for next use if validation fails.
The state of the click variable will remain true after first click and will further stop multiple clicks, unless page reloads or we reset the variable manually through code.

How do I permanently store input from an HTML text field into a jQuery variable?

jQuery
$(document).ready(function(){
var guess;
$('#submit').on("click", function() {
guess = $('#guess-value').val();
$("#value").text(guess);
alert(guess);
});
alert(guess);
});
HTML
<div id='game'>
<form id='user-input'>
<input type='text' id='guess-value' placeholder='1-100'></input>
<button id='submit'>Submit</button>
</form>
<h4 id='guess-count'>Attempts left: <span id="attempts">6</span></h4>
</div>
<h4 id='checker'>The value entered is <span id="value">?</span></h4>
I've provided snippets of my HTML and jQuery code above. I am trying to store a number that has been entered into a text field, into a jQuery variable called guess after pressing a submit button.
The following happens occurs:
When I enter a number into the field and press submit, I get an alert showing the value I entered. After closing the event I get another alert that is supposed to show the value of 'guess' and the value is undefined.
This happens even though I declared the variable guess outside of the click event. Why is this and how do I permanently store the value?
You are using a <form> element to ask for user input. The problem with a form, is that when it submits, it wants to navigate away from (or refresh) the page. When the page refreshes, all js is lost.
Simple fix: don't use a form (you can use a DIV instead).
Alternatively, you can tell the form to NOT do its default action of submitting by using event.preventDefault():
jsFiddle Demo
HTML:
<div id='game'>
<form id='user-input'>
<input type='text' id='guess-value' placeholder='1-100'></input>
<button id='submit'>Submit</button>
</form>
<h4 id='guess-count'>Attempts left: <span id="attempts">6</span></h4>
</div>
<h4 id='checker'>The value entered is <span id="value">?</span></h4>
<input type="button" id="myButt" value="Show Value" />
jQuery:
var guess;
$('#submit').on("click", function (evnt) {
guess = $('#guess-value').val();
$("#value").text(guess);
alert(guess);
evnt.preventDefault();
});
$('#myButt').click(function(){
alert( guess );
});
Further Notes:
Note that the 2nd alert(guess) in your posted code will occur immediately upon document.ready. I mean, immediately -- as soon as the DOM is ready. Before anything has been put into guess. That is why it returns undefined.
That is probably not what you want. Code example above adds a button to allow you to view that variable's contents when desired.
The function : $("#value").text(guess) is not corret in this case, replace it with :
$("#value").empty().append(guess);
you should wait to be .ready() in order to submit();
give me feedback please. enjoy :)
The 'guess' variable is out of the click event handler but it's in the ready event handler; So the second alert box will be shown exactly once when the page is loaded. It will then be undefined. The click events will occur later.

Get textbox value through button in popup

I am a newbie to chrome-extension/java script development and I am stuck at the following exercise.
I created a popup with a button and a textbox. I wanted to pass the textbox value to an alert when the submit button is pressed. I have the following code so far:
popup.html
<div id="popup"></div>
<form name="q">
<input name="query" id="userQuery" type="text" />
<button id="button1">Submit</button>
<!-- <input type="button" name="button" value="query" /> -->
</form>
popup.js
document.addEventListener('DOMContentLoaded', function () {
console.log(document.getElementById('userQuery'));
document.getElementById('button1').addEventListener('click', myAlert(document.getElementById('userQuery')));
});
function myAlert(query){
alert(query.value)
}
However, I get "null" as query.value so the alert comes empty.
I also noticed that when the extension is clicked for the popup, I get an alert as well, which I don't understand why, I used both 'click' and 'onclick' but I get the same issue.
Any hint or help will be much appreciated!
One way to do it:
document.getElementById('button1').addEventListener('click', function() { myAlert(document.getElementById('userQuery')); });
In your code, the expression myAlert(document.getElementById('userQuery')) is evaluated when addEventListener is called. That's why you see a blank alert when the page loads. Instead you need to pass a function, that will be executed when the click event happens.
Try this $("#userQuery").val() OR document.getElementById("userQuery").value
instead of document.getElementById('userQuery')

two submit buttons, with confirmation pop up only on one submit button

I have two submit buttons in a form that Lets user Update/ Delete content. I want a confirm pop only if the user clicks Delete button.
<html>
<head>
<script type="text/javascript">
function confirmation() {
// I need to know which submit button was pressed.
if (value==Delete){
var answer = confirm("Cancel?")
if (answer){
return true;
//Continue as intended
}
else{
return false
}
}
}
</script>
</head>
<body>
<form id="Edit_Data">
//form input fields go here
<input name="action" type="submit" onclick="confirmation()" value="Update">
<input name="action" type="submit" onclick="confirmation()" value="Delete">
</form>
</body>
</html>
Any Ideas?
First of all you have several problems with your code. The value in your if statement is an undefined variable secondly you need to put quotes around the delete. Here is working fiddle http://jsfiddle.net/SMBWd/ and the relevant code change. Also, I would encourage you to look how to do this without using javascript in your HTML.
function confirmation(e) {
// I need to know which submit button was pressed.
if (e.value=='Delete'){
and in the HTML
<input name="action" type="button" onclick="confirmation(this)" value="Update">
<input name="action" type="button" onclick="confirmation(this)" value="Delete">
For your onclick event definition in the html tag, why not call separate functions?
The simplest way would be to NOT call the javascript on the Update button.
If your form is static, then you do this in your IDE. If it's dynamic, then the dynamic code can create the form element accordingly.
If the form elements are generated automatically, then you should setup an event handler in JavaScript dynamically. Find all elements of type input with type attribute button or submit, and assign
elems[i].onclick = confirmation;
You'd then get the event object as a method parameter, and you could query that for the value of the button.

Javascript onsubmit causing page to refresh

Really simple form
<form id="addDonor" name="addDonor" onsubmit="addDonor(); return false;" action="" method="post" enctype="multipart/form-data">
<div class="sectionHeader">Add New Donor</div>
<div class="formRow"><label>Name</label> <input class="inputText fullTextBar" type="text" name="userName">
<div class="formRow"><button style="margin-left:350px; width: 80px" type="button" class="publish">Add Donor</button></div>
</form>
And the addDonor function
<script type="text/javascript">
function addDonor(){
alert("test");
return false;
}
</script>
Eventually that function will include some jquery ajax to submit the info. But, baby, steps. Right now I can't even get the alert to show up. Also, when I hit "Enter" on my keyboard, the whole page refreshes, when I press "Add Donor" nothing happens.
I'm sure it has to be a simple problem. I think it's one of those things that I just need someone else's eyes to point out.
Try assigning the onsubmit event in javascript:
document.getElementById("addDonor").onsubmit = function () {
alert("test");
return false;
}
The problem is that your function is named addDonor and your element is addDonor. Every element with an id has an object created under document to identify it. Try alert(addDonor) in the inline onsubmit to see that it alerts an HTML element, not a function. Inline functions execute in a scope chain inside document, so addDonor points to document.addDonor before it reaches window.addDonor (your function).
you should change your <button> to an <input type="submit"> (as #fireshadow52 suggested) that should fix your problem. you should try the Wc3 Schools online javascript tester to try out simple javascripts before you put it in a page, or any other one that you prefer. google has something along these lines. also, you can normally try the javascript console on your respective browser.
Your button is explicitly set to type="button", which won't make it submit the form. Change it to <button type="submit">, or to <input type="submit"> if you prefer (I like the styling options of <button> myself).

Categories