Cannot uncheck checkbox - javascript

I am trying to uncheck a checkbox once my form is submitted
on the html side I have the following
<form class="form contact-form" id="contact_form">
<input type="checkbox" id="store_pickup" name="pickup" value="pickup" onclick="storeDetails()">
<label for="store_pickup">Store Pickup</label>
....
And then I have an existing JS file for the form which work for all other input types but Checkbox
$(document).ready(function(){
$("#submit_btn").click(function(){
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if (user_name == "") {
$('input[name=name]').css('border-color', '#e41919');
proceed = false;
}
if (user_email == "") {
$('input[name=email]').css('border-color', '#e41919');
proceed = false;
}
if (user_message == "") {
$('textarea[name=message]').css('border-color', '#e41919');
proceed = false;
}
//everything looks good! proceed...
if (proceed) {
//data to be sent to server
post_data = {
'userName': user_name,
'userEmail': user_email,
'userMessage': user_message
};
//Ajax post data to server
$.post('contact_business.php', post_data, function(response){
//load json data from server and output message
if (response.type == 'error') {
output = '<div class="error">' + response.text + '</div>';
}
else {
output = '<div class="success">' + response.text + '</div>';
//reset values in all input fields
$('#contact_form input').val('');
$('#contact_form textarea').val('');
// $('#store_pickup').attr('checked', false);
// $("#store_pickup").prop('checked', false);
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
return false;
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function(){
$("#contact_form input, #contact_form textarea").css('border-color', '');
// $("#store_pickup").attr('checked', false);
// $("#store_pickup").prop('checked', false);
$("#result").slideUp();
});
});
I've tried the two following statment commented out in the code but these do not work, can anyone assist me. Thank you!

You can toggle the checked attr of a HTML input of type="checkbox" with
$( elem ).prop('checked', false);
$( elem ).prop('checked', true);
You can check the current state of the checked property of the checkbox with
$( elem ).prop('checked')
You can also use Chrome Inspect tool to view/test the current properties of a DOM element by selecting the element and then viewing the 'properties' tab.
https://developers.google.com/web/tools/chrome-devtools/inspect-styles/edit-dom
Note: In my version of Chrome I have to deselect and then re-select the DOM element to see the properties refresh after modifying a property value with the above JS.

It's the presence of absence of a checked attribute that controls whether the checkbox is checked. Setting the value of the attribute has no effect.
So you need
$("#store_pickup").removeAttr('checked');

Related

jQuery - placeholder values after submiting form contact

I want to improve my form contact using jQuery. I want to clear input fields after clicking and show placeholders values on submit button. I have placeholders in my input fields and want to load them into variable and show them after ajax post method.
<input type="text" name="name" placeholder="Name" data-error="Please write name">
and jQuery code:
form.on("submit", function(e) {
e.preventDefault();
var hasErrors = false;
$('div.error_message').remove(); // Remove any old errors when submitting the form
fields.each(function(i, elem) {
var field = $(elem),
empty = $.trim(field.val()) === "",
errors = field.data("error");
if (empty) {
hasErrors = true;
field.after('<div class="error_message">' + errors + '</div>'); // add new error messages
field.toggleClass("form_error", empty);
}
});
if (!hasErrors) {
var formData = $(this).serializeArray();
$.post(form.attr("action"), formData, function(data) {
console.log(data, true);
$(".przycisk").on("click", function() {
var placeholder = $("input[placeholder]");
console.log(placeholder);
$("input, textarea").val(placeholder);
});
} else {
}
return false;
});
you have to say wich attribute from input do you want to use.
in jquery is so: .attr('attributeName')
now you can select your any attribute (like placeholder)
change your code like this:
$("input, textarea").val(placeholder.attr('placeholder'));
see my code here :
https://codepen.io/miladfm/pen/ZyOEWX

localStorage : store checkboxes automatically checked

I have something like this in php:
if(isset($_POST['submit']){
$check = in_array($row['service_object_id'], $values) ? 'checked' : '';
}
echo '<input type="checkbox" class="faChkRnd" id="'.$row['service_object_id'].'" name="list[]" value="'.$row['service_object_id'].'" '.$check.'>';
Each time I press a submit button, it will check the checkboxes with values inside $check.
It's working good but I want to store the checkboxes checked in localStorage automatically after pressing the button.
I already use this script to store them after click, but it won't work automatically :
<script type = "text/javascript">
$('.faChkRnd').on('click', function() {
var fav, favs = [];
$('.faChkRnd').each(function() { // run through each of the checkboxes
fav = {id: $(this).attr('id'), value: $(this).prop('checked')};
favs.push(fav);
});
localStorage.setItem("favorites", JSON.stringify(favs));
});
$(document).ready(function() {
var favorites = JSON.parse(localStorage.getItem('favorites'));
if (!favorites.length) {return};
console.debug(favorites);
for (var i=0; i<favorites.length; i++) {
console.debug(favorites[i].value == 'on');
$('#' + favorites[i].id ).prop('checked', favorites[i].value);
}
});
</script>
Any ideas ? Thank you !
you shound check type of favorites[i].value. string or boolean !?
string :
if(favorites[i].value == "true") {
$('#' + favorites[i].id ).prop('checked',true);
}
boolean :
$('#' + favorites[i].id ).prop('checked',favorites[i].value);
example :
string : https://jsfiddle.net/utm4za2p/1/
boolean : https://jsfiddle.net/utm4za2p/3/
You can use submit method.
You have a form with the submit button and you have to change it to just a regular button.
And you should put
$('.yourForm').submit()
to the end of click handler where you save the values to the localStorage.
Because when you press the submit button it may triggered before your click handler.
You need save values first and then submit form.

Get Js Value in Laravel Controller

How do I get the js value in Laravel controller. I want to pass the value from the hidden fields to be saved in the db, but to my surprise it saves empty records for these fields. When I logged the values on the console, I am seeing it but it is not passed as the value to the controller. What better way am I to handle this?
public function store(UserContactRequest $userContactRequest)
{
$phone = $userContactRequest->phone_output;
if(Auth::user()) {
if($userContactRequest->isMethod('post')) {
$userContact = UserContact::firstOrNew(array('user_id'=>Auth::user()->id));
$userContact->phone = $phone;
$userContact->save();
return redirect()->route('userContactIndex')->with('message', 'Your question has been posted.');
}else{
return redirect('user/contact/create')->withErrors($userContactRequest)->withInput();
}
}
}
This is the blade file
<TH>FIELD</TH><TH>DECRIPTION</TH>
<input type="hidden" name="phone_output" id="phone_output">
<TR><TD><div>{!! Form::tel('phone', Input::old('phone'), ['class'=>'mid first-input-div', 'placeholder'=>'8023472436', 'id'=>'phone']) !!}</div></TD><TD class="font-description"><SPAN id="errNm1"><STRONG><I>FIRSTNAME</I></STRONG></SPAN> field requests the input of your surname or family name. Only <SPAN><STRONG><I>alphabets</I></STRONG></SPAN> are accepted as valid inputs. </TD></TR>
THis is the js file:
$("#phone").intlTelInput();
var input = $("#phone"),
output = $("#phone_output");
input.intlTelInput({
nationalMode: true,
utilsScript: "http://localhost:88/build/js/utils.js" // just for formatting/placeholders etc
});
// listen to "keyup", but also "change" to update when the user selects a country
input.on("keyup change", function() {
var intlNumber = input.intlTelInput("getNumber");
if (intlNumber) {
output.text("International: " + intlNumber);
console.log(intlNumber);
} else {
output.text("Please enter a number below");
}
});
You should use output.val() to set a value for the hidden input field.
You have used output.text() instead.
Updated snippet :
input.on("keyup change", function() {
var intlNumber = input.intlTelInput("getNumber");
if (intlNumber) {
output.val("International: " + intlNumber);
console.log(intlNumber);
} else {
output.val("Please enter a number below");
}
});

php and javascript form validation issue

I have created a form using bootstrap and am using javascript for form validation and then a php script to grab the post data and display it
the basic structure is the following and I have made this as minimal as I could to address this specific issue. The issue I am having is that the script to check for the form validation works perfectly in the <script> tags at the end of the body, but instead of preventing the page from being submitted as it should it still processes to the next page with the form's contents that are being made through the php post action when the form is indeed not filled out correctly.
Why is this? Should the form validation still not stop the page from moving on to the post data since the validation is returning false if the form has not been submitted correctly. All the form validation alerts pop up correctly and I;m getting no console errors after checking, or do I need to perform an additional check to only process the post data if the form is valid?
<html>
other tags.....
<body>
<form name = "OrderForm" action = "process_order.php" onsubmit = "orderbutton" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
</body>
<script>
function CheckForm() {
var Name = document.getElementById("Name");
var fries = document.forms.OrderForm.FryRadio;
var fryyes = fries[0].checked
var fryno = fries[1].checked
var bool = true;
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked))) {
bool = false;
}
else if (!(fryyes || fryno)) {
bool = false;
}
if (!(bool)) {
alert("Please fill out all of the required fields.");
return false;
}
else {
alert("Your order is being submitted");
console.log("Submitted")
}
};
</script>
</html>
You should call function on submit , I dont know what are you doing with current onsubmit='...'
So use following, call function when you submit the form.
<form name = "OrderForm" action = "process_order.php" onsubmit = "return CheckForm()" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
For demo : Check Fiddle
first of all what you can do is:
you do not need the !fryes in another if statement:
you can do it also in the first if:
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked)) || ( (!(fryyes || fryno))) {
bool = false;
}
also what you can do is if bool is false, disable your submit button if there is any?
you can also do an onchange on the texboxes, that way you can validate each text box or checkbox one by one. and have the bool true and false?
I did something like this on jquery long time ago, for validation, where I checked each texbox or dropdown against database and then validate, aswell..
The code is below
<script>
$(document).ready(function(){
var works=true;
//Coding for the captcha, to see if the user has typed the correct text
$('#mycaptcha').on('keyup',function(){
if($('#mycaptcha').val().length>=5){
$.post("user_test/captcha_check.php",
{
// userid: $("#userlogin").val(),
mocaptcha: $("#mycaptcha").val(),
},
function(data,status){
if(data==0){
document.getElementById("final_error").innerHTML="Captcha did not match";
works=false;
}
if(data==1){
works=true;
document.getElementById("final_error").innerHTML="";
}
});
}
});
//Works like a flag, if any mistake in the form it will turn to false
//Coding the submit button...
$('#submitbtn').on('click',function(){
var arrLang = [];
var arrPrf = [];
uid = $("#userid").val();
capc = $('#mycaptcha').val();
pwd = $("#pwd1").val();
fname = $("#fname").val();
lname = $("#lname").val();
email = $("#memail").val();
pass = $("#pwd2, #pwd1").val();
daysel = $('#dayselect').val();
monthsel = $('#monthselect').val();
yearsel = $('#yearselect').val();
agree_term = $('#agree_box').prop('checked');
//checks if the textboxes are empty it will change the flag to false;
if((!uid) || (!capc) ||(!fname) || (!lname) || (!email) || (!pass) || (!daysel) || (!monthsel) || (!yearsel) || (!agree_term)){
works=false;
}
if(!works){
document.getElementById('final_error').innerHTML ="<font size='1.3px' color='red'>Please fill the form, accept the agreement and re-submit your form</font>";
}
else{
works=true;
//A jquery function, that goes through the array of selects and then adds them to the array called arrLang
$('[id=lang]').each(function (i, item) {
var lang = $(item).val();
arrLang.push(lang);
});
//A jquery function, that goes through the array of select prof and then adds them to the array called arrprf
$('[id=prof]').each(function (i, item) {
var prof = $(item).val();
arrPrf.push(prof);
});
var data0 = {fname: fname, mlname : lname, userid : uid,password:pwd, emailid : email, mylanguage : arrLang, proficient : arrPrf, dob : yearsel+"-"+monthsel+"-"+daysel};
//var json = JSON2.stringify(data0 );
$.post("Register_action.php",
{
// userid: $("#userlogin").val(),
json: data0,
},
function(data,status){
if(data==1){
//alert(data);
window.location = 'Registered.php';
}
document.getElementById("userid_error").innerHTML=data;
});
}
});
//to open the agreement in a seperate page to read it..
$("#load_agreement").click(function () {
window.open("agreement.html", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
});
//A code that loads, another page inside the agreement div
$( "#agreement" ).load( "agreement.html" );
//This part here will keep generating, duplicate of the language and profeciency box, incase someone needs it
$('#Add').click(function(){
//we select the box clone it and insert it after the box
$('#lang').clone().insertAfter("#lang").before('<br>');
$('#prof').clone().insertAfter("#prof").before('<br>');
});
//this part here generates number 1-31 and adds into month and days
i=0;
for(i=1; i<=31; i++){
$('#dayselect').append($('<option>', {value:i, text:i}));
if(i<=12){
$('#monthselect').append($('<option>', {value:i, text:i}));
}
}
//this code here generates years, will work for the last, 120 years
year=(new Date).getFullYear()-120;
i = (new Date).getFullYear()-16;
for(i; i>=year; i--){
$('#yearselect').append($('<option>', {value:i, text:i}));
}
//Regex Patterns
var pass = /^[a-z0-9\.\-\)\(\_)]+$/i;
var uname = /^[a-z0-9\.\-]+$/i;
var mname = /^[a-z ]+$/i;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
//When the Last Name texbox is changing this will be invoked
$("#fname").keydown(function(){
//comparing the above regex to the value in the texbox, if not from the box then send error
if(!mname.test($("#fname").val())){
//fill the textbox label with error
document.getElementById("fname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid FirstName</font>";
$("#fname").css("border-color","rgba(255,0,0,.6)");
works=false;
}
else{
$("#fname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("fname_error").innerHTML="";
works = true;
}
});//end of fname onchange
//When the Last Name texbox is changint this will be invoked
$("#lname").keydown(function(){
//comparing the above regex to the value in the texbox
if(!mname.test($("#lname").val())){
//fill the textbox label with error
document.getElementById("lname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid LastName</font>";
$("#lname").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
$("#lname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("lname_error").innerHTML="";
works = true;
}
});//end of lname on change
//When the userid textbox is chaning,this will be invoked
$("#userid").keydown(function(){
//comparing the above regex to the value in the texbox
if(!uname.test($("#userid").val())){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid UserId</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
works=false;
}
/*
else if($("#userid").val().length<4){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Minimum user length is 4</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
//disable the submit button
//$('#submitbtn').attr('disabled','disabled');
works=false;
}
*/
else{
$("#userid").css("border-color","rgba(0,0,0,.3)");
$.post("user_test/user_email_test.php",
{
// userid: $("#userlogin").val(),
userid: $("#userid").val(),
},
function(data,status){
document.getElementById("userid_error").innerHTML=data;
});
works = true;
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#memail").keydown(function(){
//comparing the above regex to the value in the texbox
if(!emailReg.test($("#memail").val())){
//fill the textbox label with error
document.getElementById("email_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid Email</font>";
$("#memail").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
works = true;
$.post("./user_test/user_email_test.php",{
useremail: $("#memail").val(),
},
function(data,status){
document.getElementById("email_error").innerHTML=data;
$("#memail").css("border-color","rgba(0,255,0,.3)");
works = true;
});
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#pwd2").keyup(function(){
//checking length of the password
if($("#pwd2").val().length<10){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Please enter a password minimum 10 characters</font>";
//$('#submitbtn').attr('disabled','disabled');
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
works=false;
}
//checking if the password matches
else if($("#pwd1").val()!=$("#pwd2").val()){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Passwords do not match</font>";
//$('#submitbtn').attr('disabled','disabled');
works=false;
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
}
else{
$("#pwd1, #pwd2").css("border-color","rgba(0,0,0,.3)");
document.getElementById("pwd_error").innerHTML="";
//comparing the above regex to the value in the texbox and checking if the lenght is atleast 10
if(!pass.test($("#pwd2").val())){
//fill the textbox label with error
document.getElementById("pwd_error").innerHTML="<font color='red' size='1px' family='verdana'>Your password contains invalid character, Please use: a-z 0-9.( )_- only</font>";
$("#pwd1, #pwd2").css("border-color","rgba(255,0,0,.6");
works = false;
}
else{
$("#pwd1 , #pwd2").css("border-color","rgba(0,255,100,.6)");
works = true;
}
}
});//end of change
});//end of document ready
</script>

Change form field color if the value has change

I'm gettig a bit lost with some javascript logic.
I have a form with 3 text fields.
They show a default value through a javascript (no placeholder).
When the form is focused, the value is cleared and when the form is blurred, the default value is restored if the field value hasn't been change.
I have to write some conditional logic to ensure that the field text color is changed from grey (default placeholder value) to black if the value is changed.
The 3 fields have a different default value. I tried to write a general script on Blur to check the value of the current field to test it against the default value.
$fields = $('#webform-component-group-1 .webform-component-watermarked');
var keys = [];
var values = [];
console.log($fields.length);
$fields.each(function(){
keys.push($(this).attr('id'));
values.push($(this).val());
$(this).blur(function(){
console.log($(this).val());
console.log($(this).val() !== values[keys.indexOf($(this).attr('id'))]);
});
});
but my test always return true as the placeholder value is not restored when I run the test on blur.
What would be the best way to handle this problem?
Cheers
Using jQuery, you could do it like this:
Assuming the following HTML
<div id='fields'>
<input value='start1' class='placeholder' />
<input value='start2' class='placeholder' />
</div>
JavaScript
$('#fields input').each(function(){
// Save initial placeholder values
$(this).data('placeholder', $(this).val());
}).on("focus", function(){
// Remove placeholder value and color on focus
if( $(this).val() === $(this).data('placeholder') ){
$(this).val('').removeClass('placeholder');
}
}).on("blur", function(){
// Restore placeholder on blur if input is empty
if( $(this).val().length === 0 ){
$(this).val($(this).data('placeholder')).addClass('placeholder');
}
});
CSS
input.placeholder{
color:#ccc;
}
input{
color:#000;
}
Fiddle: http://jsfiddle.net/uWPJC/
Try to play with this code , you will get what u looking for
var pass1 = document.getElementById('password');
var pass2 = document.getElementById('vpass');
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
}
else{
pass2.style.backgroundColor = badColor;
}

Categories

Resources