Make text appear when submit button clicked and checkbox is unchecked - javascript

I am trying to create an agree to terms and agreements. However, when the button is unchecked and the user hits submit, I want it to present the user with an alert telling him to agree to the terms. At first, I made it to where the user couldn't even click on the submit button when the checkbox is unchecked, however, I want the user to be able to click it so he can be alerted with an error. I can't seem to get my code to work no matter what.
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('submit');
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
if(document.getElementById('submit').click() & document.getElementById("myCheck").checked = false;){
alert("Hello! I am an alert box!!");
}
}
<input type="checkbox" id="checkme"/>
I agree to the terms & service<br />
<input type="submit" name="sendNewSms" class="md-trigger blue-texture postbit-button-big md-pointer" data-modal="modal-five" id="submit" value=" Send " onclick="$('.md-modal').removeClass('md-show');" disabled/>

I want the user to be able to click it so he can be alerted with an error
Remove the disabled from the submit button.
Remove the checker.onchange = function(){
Make sure to event.preventDefault(); browser triggering form submits or other default evett actions
All you need:
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('submit');
sendbtn.onclick = function( event ){
event.preventDefault();
if(!checker.checked){
alert("You must agree to our terms of service");
}
};
Note that you might want to do the above not on button Click but on formID.onsubmit (the form can always be submitted even without a Button click. Not seeing your form this is all I can suggest.)
P.S:
Developer Console (access by F12 and click Console) helps to debug such errors like &/&& =/=== missing ; etc...
P.S2: when using only JS a handy function to fast-get an element by ID can be achieved with a nice little function i.e:
function ID(id){return document.getElementById(id);} // ...and use like:
var submitBtn = ID("submit");

document.getElementById("myCheck").checked = false; is assigning it to false. If you want to check if it is false, you need this
document.getElementById("myCheck").checked === false;

Remove disabled from submit and the other js and use this:
$('#submit').click(function(e) {
if (!$('#checkme').is(':checked')) {
e.preventDefault();
alert('Check the box!');
} else {
$(e.currentTarget).parent('form').first().submit();
}
});

Related

Stop a form from submitting

I have a form which is submitted using Ajax.
If a checkbox is checked (receive latest offers and such), I would like to prevent the form from being submitted, if the fields are not filled out.
If the checkbox is not checked, then I don't care if the fields are filled out, and the form can be submitted even if empty.
The problem I'm currently having is, that the form is being submitted even if the checkbox is checked and the fields are empty.
I tried return false, event.stopImmediatePropagation(), event.stopPropagation() and event.preventDefault();. None of them prevent the form from submitting.
function check() is attached to the submit button.
Any and all advice is welcome.
If I can provide any additional information, let me know.
Thank you
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
return false; //event.preventDefault()//etc etc
}
if (!email.validity.valid) {
showEmailError();
return false; //event.preventDefault()//etc etc
}
};
};
setTimeout(function() {
document.getElementById("allow").addEventListener("click", sendAjax);
}, 1);
<button id="allow" onclick="check()">
<span id="a"></span>
</button>
As chandan suggested, I edited function check() and it works.
RollingHogs answer should also work, but the button I'm using is not type submit, as a few other ajax functions need to run before the form is submitted, so I can not accept that.
Anyway, this is the code that does the job:
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if(!fname.validity.valid && !email.validity.valid){
showNameError();
showEmailError();
}else if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
}else if(!email.validity.valid) {
showEmailError();
}else{
sendAjax();
}
}else{
sendAjax();
};
};
I guess the problem is that you stop button.onclick from propagation, not form.onsubmit. Try moving check() from onclick to onsubmit:
<form id="fname" ... onsubmit="check(event)">
<button id="allow" type="submit"></button>
</form>
Function check() should work without any edits then.
Also, see code from this question

Checkbox Javascript disable button

I have an array of users in php that i send to the view (in laravel) and do a foreach to list all users in table. For now it is ok. I have a "send" button that appear disable but i want to put visible when i click on the checkbox.
I put this javascript code:
<script type="text/javascript">
Enable = function(val)
{
var sbmt = document.getElementById("send"); //id of button
if (val.checked == true)
{
sbmt.disabled = false;
}
else
{
sbmt.disabled = true;
}
}
</script>
and call the function onClick method of checkbox:
onclick="Enable(this)"
But the problem is when i click on the check box only the first button send works and appear visible. If i click for example in check box of user in position 2,3,4...etc the buttons send of these users stay disabled, only the first appear visible. This code only work to the first position of send button.
I appreciate your help :)
Regards
You pass element to function Enable, but treat it as value. You should extract value from element before other actions.
You hardcoded button id in the function. It shout be passed outside and should differs for each button.
Enable = function(checkbox, btnId)
{
document.getElementById(btnId).disabled = !checkbox.checked; // ← !
}
<button id="send1" disabled>SEND</button>
<input type="checkbox" onclick="Enable(this, 'send1')"><br>
<button id="send2" disabled>SEND</button>
<input type="checkbox" onclick="Enable(this, 'send2')"><br>
<button id="send3" disabled>SEND</button>
<input type="checkbox" onclick="Enable(this, 'send3')">
The reason is that you are using id element to activate button.
What you can do is set id for each of your send button while you loop and pass it from your click your function and use it enable it.
<script type="text/javascript">
Enable = function(val, id)
{
var sbmt = document.getElementById("send-"+ id ); //id of button
if (val.checked == true)
{
sbmt.disabled = false;
}
else
{
sbmt.disabled = true;
}
}
</script>
and your click button looks like this
onclick="Enable(this,id)"
Hope you understood.

Show error after button click Javascript

After my button click, I would check if my text fields are not empty. My check works, but if I show my message it's show for a few seconds. Probably the duration of my button click. Here is some code I've tried.
<form>
<div id="errorblock">
<p id="errortext">Error.</p>
</div>
<!-- here are my input fields-->
<button>Send</button>
</form>
This is where I add my event listener after initialisation of the page:
document.getElementsByTagName("button")[0].addEventListener("click", function(){
sendEmail();
});
function sendEmail() {
//check if all fields are fill in. If not do this code;
document.getElementById("errortext").innerHTML = "Fill in all the fields please.";
var errorblock = document.getElementById("errorblock");
errorblock.style.visibility = "visible";
errorblock.style.height = "46px";
}
Can anyone help me?
Thanks
By default HTMLButtonElement has type="submit". It means that on button click the form is submitted. You need to make sure you prevent this submission in case of errors in the form. For example by calling preventDefault methods of the event object:
document.getElementsByTagName("button")[0].addEventListener("click", function (e) {
if (!sendEmail()) {
e.preventDefault();
}
});
function sendEmail() {
//check if all fields are fill in. If not do this code;
document.getElementById("errortext").innerHTML = "Fill in all the fields please.";
var errorblock = document.getElementById("errorblock");
errorblock.style.visibility = "visible";
errorblock.style.height = "46px";
// if there are errors return false
// return true if input is correct
return false;
}
Also I recommend to listen onsubmit event on the form instead of button click event:
document.querySelector("form").addEventListener("submit", function (e) {
if (!sendEmail()) {
e.preventDefault();
}
});

Avoid a form field when alerting the user is leaving the page without saving form changes

Hi all,
The following code warns the user that he/she has not submitted form changes when he/she tries to leave the webpage without clicking the submit button.
formmodified = 0;
$('form *').change(function(){
formmodified = 1;
});
window.onbeforeunload = confirmExit;
function confirmExit() {
if (formmodified == 1)
{
return "You need to save your changes before you leave the page";
}
}
$("input[name='btnPost']").click(function()
{
formmodified = 0;
});
It works great, but I need this code to forget about a field in the form.
The field is this one a photo file uploader:
<input type="file" name="photo">
With the code as it is, the message alerting you are leaving the page shows before filling the rest of the form and it is quite confusing for the users that's why I need this field to be avoided.
Thanks a lot
Use this;
$('form *').change(function(){
if ($(this).attr("name") != "photo") {
formmodified = 1;
}
});
If you want to exclude an element from selector, you can use :not().
$('form *:not(input[name="photo"])').change(function(){
formmodified = 1;
});
Or with function:
$('form *').not('input[name="photo"]').change(function(){

ASP.NET Post-Back and window.onload

I got a function which checks if some input fields are changed:
var somethingchanged = false;
$(".container-box fieldset input").change(function() {
somethingchanged = true;
});
And a function which waits on window.onload and fires this:
window.onbeforeunload = function(e) {
if (somethingchanged) {
var message = "Fields have been edited without saving - continue?";
if (typeof e == "undefined") {
e = window.event;
}
if (e) {
e.returnValue = message;
}
return message;
}
}
But if I edit some of the fields and hit the save button, the event triggers, because there is a post-back and the fields have been edited. Is there anyway around this, so the event does not fire upon clicking the save button?
Thanks
When I do this pattern I have a showDirtyPrompt on the page. Then whenever an action occurs which I don't want to go through the dirty check I just set the variable to false. You can do this on the client side click event of the button.
The nice thing about this is that there might be other cases where you don't want to prompt, the user you might have other buttons which do other post backs for example. This way your dirty check function doesn't have to check several buttons, you flip the responsability around.
<input type="button" onclick="javascript:showDirtyPrompt=false;".../>
function unloadHandler()
{
if (showDirtyPrompt)
{
//have your regular logic run here
}
showDirtyPrompt=true;
}
Yes. Check to see that the button clicked is not the save button. So it could be something like
if ($this.id.not("savebuttonID")) {
trigger stuff
}

Categories