For eaxmple in case the checkbox is not checked and the user hits the submit we need to show the error message "please check the checkbox". in case if the checkbox is checked and the hyper link is not clicked by the user we need to show the error message "Please click the link".
My Code
<script>
var state = 0;
$("#AcceptMe").click(function()
{
state=1;
});
if(state == 0)
{
alert("please click");
}
</script>
</head>
<body>
<form>
<a id="Link1" href="#">click</a>
<input type="checkbox" id="AcceptMe">
<input type="submit" name="submit">
</form>
This is not a good solution, because when the user clicks twice, he/she unchecks the checkbox, but the "state" would still be 1.
Check if the checkbox is checked like this:
var isChecked = $('#AcceptMe').is(':checked')?true:false;
Now the "isChecked" variable will contain true or false so you should first give the submit button an ID and type="button" (otherwise it will try to submit):
<input type="button" value="submit" name="submit" id="submitForm"/>
Add a clickHandler for the link like this:
var linkClicked = false;
$('#Link1').click(function(){
linkClicked = true;
});
Then under that function your javascript add a clickhandler to the submitbutton:
$('#submitForm').click(function(){
var isChecked = $('#AcceptMe').attr('checked')?true:false;
if(isChecked){
alert('checked!');
if(linkClicked){
alert('Link clicked!');
}
else{
alert('Click link first!');
}
else{
alert('please check the checkbox!');
}
});
JSFiddle here: http://jsfiddle.net/8o4an9xf/
Please note that you should add target="_blank", because the link will otherwise override the document.location. Or you could open the content you want to show in a modal window (which is nicer).
I think you must use "return false"
My code is clear and simple.
If its not matter for you to have in-line code try below:
<body>
<form>
<a id="Link1" href="#" onclick="$('#Link1').addClass('visited');
alert('add \'visited\' class to \'#Link1\'');">
</a>
<input type="checkbox" id="AcceptMe" />
<input type="submit" name="submit" onclick="
if( $('#AcceptMe').is(':checked')){
alert('checkbox is :' + $('#AcceptMe').is(':checked'));
if(!$('#Link1').hasClass('visited')){
alert('please visit link1');
return false;
};
}else{
return false;
}
" />
</form>
</body>
Related
I have two forms (consist with input,textarea,checkbox) in a page. I want check emptiness of these forms separately on click seperate button.
I use the following script. But it shows empty message if any of these form input is empty.
$('#submit').click(function(e) {
var empty = false;
$('input, textarea').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
alert("empty");
e.preventDefault();
}
else {
document.getElementById("contact").submit();
}
})()
Never assign stuff to submit buttons
Do not submit a form from a submit button if you have chosen to use preventDefault if something wrong. It could submit the form twice
$(function() {
// on the submit event NOT the button click
$('form').on("submit", function(e) { // any form - use .formClass if necessary to specific forms
var empty = false;
$("input, textarea", this).each(function() { // this form's inputs incl submit
if ($.trim($(this).val()) == "") { // trim it too
console.log(this.name,"empty")
empty = true;
return false; // no need to continue
}
});
if (empty) {
alert(this.id + " is empty"); // or set a class on the div
e.preventDefault(); // cancel submission
}
});
});
div {
border: 1px solid black;
width:500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form id="form1">
<div>
<input type="text" value="" name="field1" /><br/>
<textarea name="field2"></textarea><br/>
<input type="submit" value="Submit" />
</div>
</form>
<hr/>
<form id="form2">
<div>
<input type="text" value="" name="field3" /><br/>
<textarea name="field4"></textarea><br/>
<input type="submit" value="Submit" />
</div>
</form>
You could also add required to the fields
You need to restrain the handler to the form containing the clicked button:
$('#submit').click(function(e) {
var form = $(this).parents('form:first');
var empty = false;
$('input, textarea', form).each(function() {
// the rest is the same
I'd also like to point out that you cannot have the same ID on multiple controls, so
$('#submit')
should always return exactly one button. You should do something like this, where you distinguish the buttons by class instead:
<input type="submit" id="submitA" class="submitButton">
<input type="submit" id="submitB" class="submitButton">
and select with
$('.submitButton')
you know you can also use jquery to reset the form like so
form.resetForm();
I have some javascipt code here that validates a user form. When the user inputs the correct answer it tells them and gives them the link to the next question. At least, that's what it is supposed to do. When i click the form it reloads the page but it should not because i added return false.
the div tra holds 35
and the div usermsg is the user inputted value.
<script>
$("#submit").click(function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6<>rightanswer)
{
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else
{
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
</script>
Any ideas why this is not working?
It should be
if (clientmsg6 != rightanswer)
not
if (clientmsg6<>rightanswer)
To prevent a form submission, you need to return false on the form itself instead of on the submit button. Your code should become:
HTML
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="submit" value="Submit" />
</form>
JS (please note the line where you have clientmsg6, you have a syntax error)
$("#myform").on('submit', function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6 != rightanswer) { //This line was also wrong, should be != instead of <>
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else {
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
Alternatively, you can keep your existing code by changing your submit button to be just a plain old button, but you will lose the extra functionality of the user being able to hit the enter key and performing the same action.
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="button" value="Submit" />
</form>
Instead of using .html(), try using .text()
if #submit is a link tag otherwise use the form ID and the submit event
$("#submit").click(function(e){
e.preventDefault()
...
...
...
});
You need to attach handlers once the document has finished loading.
Wrap your script in the following
<script>
$(function() {
// script
});
</script>
I have 2 submit buttons in an HTML form.
How can I know which submit button has triggered the JavaScript function?
<script language="javascript" type="text/javascript">
function verifyData(formdata) {
// Here I want to know from which submit button this function is triggered
// I can't use type button instead of submit
// I can't use onclick handler
// I can't use JQuery.. I want to do only with javascript
}
</script>
<form onsubmit="verifyData(this);" method="post">
<input type="submit" value="submit1">
<input type="submit" value="submit2">
</form>
<button value="delete row" id="but1" onclick="disps()">delete row</button>
I want to do different actions based on the different submit buttons clicked.
It is not possible to check the button clicked through the onsubmit event. Instead move the call to verifyData() to the onclick handler of each button. Use return in the onclick call to cancel submission if false is returned by verifyData()
<script language="javascript" type="text/javascript">
function verifyData(button) {
// validate
switch (button.value) {
case "submit1":
// do somehting
break;
case "submit2":
// do somehting
break;
// ...
};
// submit the form
return true;
}
</script>
<form method="post">
<input type="submit" value="submit1" onclick="return verifyData(this);">
<input type="submit" value="submit2" onclick="return verifyData(this);">
</form>
How about putting an onclick event handler on both buttons which will set a variable to say which button was clicked?
like so:
<script language="javascript" type="text/javascript">
function verifyData(formdata) {
alert(btnClicked);
// Here I want to know from which submit button this function is triggered
// I can't use type button instead of submit
}
var btnClicked = 0;
function setSubmit(which) {
btnClicked = which; return true;
}
</script>
<form onsubmit="verifyData(this);" method="post">
<input type="submit" value="submit1" onclick="return setSubmit(1);">
<input type="submit" value="submit2" onclick="return setSubmit(2);">
</form>
Are you allowed to use the jQuery library?
If you can using this you can easily bind to each submit button based on an id.
For example:
<form id="form1" method="post">
<input type="submit" value="submit1" id="submit1">
<input type="submit" value="submit2" id="submit2" >
</form>
<script type="text/javascript">
$("#submit1").click(function(e)
{
// Do stuff when 1 is clicked.
$("#form1").submit();
});
$("#submit2").click(function(e)
{
// Do stuff when 2 is clicked.
$("#form1").submit();
});
</script>
you could also have the buttons as a type of button to avoid any issues, but you should be able to simply return false; to stop the button of type submit from... submitting
Here is how I would do it... Firstly I would use jQuery so you must include that in your document like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
It would also mean your HTML can be simplified to:
<form method="post">
<input type="submit" value="submit1"/>
<input type="submit" value="submit2"/>
</form>
Then you can use jQuery:
<script>
// When the document is ready
$(function(){
// Action performed when a submit button in the form is clicked
$("form[type='submit']").click(function(e){
// Get the value attribute
var val = $(this).val(),
validation_has_passed = false;
// If it is submit1
if(val == "submit1") {
// Validate submit 1
validation_has_passed = true;
// If it is submit2
} else if(val == "submit2") {
// Validate submit 2
validation_has_passed = true;
}
// If all validation is OK submit the form
if(validation_has_passed === true) {
$("form").submit();
}
// Ensure pressing these buttons doesn't submit the form
e.preventDefault();
});
});
</script>
I know only what I need but I do not know how to get that done.
This is the logic of the code, I really hope some of you has the solution.
How can I create in javascript or jQuery a function that will do the following?
If that checkbox is selected, when the button is clicked redirect the user to another page by passing the value of the textarea in the URL.
So that is the logic.
We have three elements.
1)The checkbox
2)The input type button
3) The textarea.
The checkbox is selected, the user clicks on the button and the user goes to another page , and the URL will include the value found in the textarea.
i.e.
http://mydomainname/page.php?ValueThatWasinTextArea=Hello World
Can you help me.
I think it is something simple for a javascript coder.
Thank you so much
$(function(){
$(':button').click(function(){
if($('input[type="checkbox"]').is(":checked")){
window.location.href = "http://mydomainname/page.php?ValueThatWasinTextArea="+ $('textarea').val();
}
});
});
**Of course if there's more than these three elements on the page, you're going to want some more specific selectors
You could subscribe to the submit event of the form and inside test if the checkbox was checked and if yes use window.location.href to redirect to the desired url:
$('#id_of_the_form').submit(function() {
var value = encodeURIComponent($('#id_of_textarea').val());
if ($('#id_of_checkbox').is(':checked')) {
window.location.href = '/page.php?ValueThatWasinTextArea=' + value;
return false;
}
});
If the button is not a submit button you can subscribe for the click event of this button and perform the same logic.
Might be some syntax problem because I code this on top of my head
<input id="myCheckbox" type="checkbox" />
<button id="myButton" onClick="buttonClick" />
<input id="myTextArea" type="textarea" />
<script>
function buttonClick()
{
var checkBox = document.getElementById('myCheckbox');
var textArea = document.getElementById('myTextArea');
if(checkBox.checked)
{
window.location = 'http://mydomainname/page.php?ValueThatWasinTextArea=' + textArea.value;
}
}
</script>
$(document).ready(function() {
$('#btnSubmit').click(function() {
if($('#chkBox').is(':checked')) {
window.location = '/page.php?passedValue=' + $('#txtField').val();
}
});
};
...
<form>
<p>
<input type="checkbox" id="chkBox"> Checkbox</input>
</p>
<p>
<input type="text" id="txtField" value="" />
</p>
<p>
<input type="submit" id="btnSubmit" value="Submit" />
</p>
</form>
I've got this simple login screen where is has a text box for the name, and a submit button. The jquery script running is this:
$(document).ready(function() {
$('#btnLogin').click( function() { validate() });
$('#loginForm').submit( function() { validate() });
});
function validate() {
if ($('#txtLogin').val() != '') {
document.cookie = 'loginID=' + $('#txtLogin').val();
$('#lblError').hide();
document.location.href = 'mainmenu.aspx';
}
else {
$('#txtLogin').text('');
$('#lblError').show();
}
}
It works when I click the button, but when I press enter, it doesn't navigate to the mainmenu.aspx. I'm following it with Chrome and it does execute the redirect just like when you press the button, but it just stays on the same page. I also put a break point in the Page_Load function (C#) of the mainmenu.aspx, but it never reaches it.
EDIT:: Here's the html
<form id="loginForm" runat="server">
<div>
<div class='theme login'>
<p>Login</p>
<input type='text' id='txtLogin' maxlength='17' />
<div><input type='button' id='btnLogin' class='button' value='Log In' /></div>
<div><span id='lblError' visible='false' text='*You must enter a valid username'></span></div>
</div>
</div>
</form>
In your form submit handler, use preventDefault() to stop the default submit behavior:
$('#loginForm').submit( function(e) {
e.preventDefault(); // swallow regular submit behavior
validate(); // your stuff
// real submit? your option
});
Reference: http://api.jquery.com/event.preventDefault/
Try making the submit element in the form just a regular button element. The browser may be intercepting something.
The reason for that is your submit still happens when you hit enter. You need to cancel the default behavior by returning false in the event handler function.
function validate() {
// ...
return false;
}
$('#loginForm').submit(validate);
$('#btnLogin').click(validate);
Edit: refer to the function directly instead of an anonymous function?
function validate() {
if ($('#txtLogin').val() != '') {
document.cookie = 'loginID='+$('#txtLogin').val();//set expire and path?
$('#lblError').hide();
location.href = "mainmenu.aspx"; //"submit"
}
else {
$('#lblError').show();
return false; //prevent submit
}
}
$(function() {
$('#btnLogin').click(validate);
$('#loginForm').submit(validate);
});
I changed both some of your HTML and jQuery code. Now it will check and submit on both Enter and when the button is clicked.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$("form").attr("action","javascript:void();"); // No action on form submission
$("input").keypress(function(e) { // Capture keys pressed
if(e.keyCode==13) { // Enter key?
validate();
}
});
$("input:button").click(function() { // Button clicked?
validate();
});
});
function validate() {
if ($("#txtLogin").val()!='') {
document.cookie="loginID="+$("#txtLogin").val();
$("#lblError").hide();
$("form").attr("action","mainmenu.aspx"); // Change form action
$("form").submit(); // Submit the form
} else {
$("#lblError").show();
}
}
</script>
HTML
<form id="loginForm" runat="server">
<div>
<div class="theme login">
<p>Login</p>
<input type="text" id="txtLogin" maxlength="17" />
<div><input type="button" id="btnLogin" class="button" value="Log In" /></div>
<div id="lblError" style="display: none;">* You must enter a valid username</div> <!-- Error message -->
</div>
</div>
</form>