On my .html
<div class="col-md-9 col-sm-9 col-xs-12">
<div class="">
<label>
<input type="checkbox" id="SMSCheckbox" class="js-switch" /> SMS
</label>
</div>
<div class="">
<label>
<input type="checkbox" id="EmailCheckBox" class="js-switch" /> Email
</label>
</div>
</div>
On my .js
$(document).ready(initialize);
function initialize() {
console.log("loaded JS");
$.ajax({
type: "GET",
url: "./getNotificationSettings.php",
datatype: "json",
success: function(response) {
var response = JSON.parse(response);
var bySMS = response[0].receiveSMS;
var byEmail = response[0].receiveEmail;
if (bySMS) {
console.log("bySMS = true");
$('#SMSCheckbox').prop('checked', true);
} else {
console.log("bySMS = false");
$('#SMSCheckbox').prop('checked', false);
}
if (byEmail) {
console.log("byEmail = true");
$('#EmailCheckBox').prop('checked', true);
} else {
console.log("byEmail = false");
$('#EmailCheckBox').prop('checked', false);
}
},
error: function(e) {
console.log(e);
}
});
}
bySMS = true
byEmail = true
I checked my console that it does go inside the if true branch but somehow my checkbox is not being selected. It's strange that I tested it on jsfiddle and it's working.
What could be the cause of this strange issue?
Not sure if it matters that to toggle the checkbox, I had to click on the wording. Clicking on the switch doesn't toggle it.
I always use .click() on checkboxes when changing the checked property doesn't work for some reason, not sure if this is a proper way of doing it.
I created a little function to handle it for you:
$.fn.setCheckbox = function(value) {
var checked = $(this).attr("checked") != "undefined" &&
($(this).attr("checked") === "checked" ||
$(this).attr("checked") === true);
if (checked != value) {
$(this).click();
}
}
Plunker: https://plnkr.co/edit/mdAzNsZnRdl2ifIT22e0?p=preview
Related
I have a bug that I could not figure out in my validation method. I have a function that validate the "code" table in my database to make sure the user can not input duplicate data. It is all working as expected and here is the code:
function validateCode() {
$('#code-error').html('')
if ($('#code').val() != '') {
$.ajax({
url: '${createLink(action:'checkCode')}',
type: 'GET',
data: {
'code': $('#code').val(),
},
// dataType:'json',
success: function (data) {
if (data == 'true') {
$('#code-error').html('Code already exist')
$(':input[type="submit"]').prop('disabled', true);
} else {
// $('#code-error').html('Code not exist')
$(':input[type="submit"]').prop('disabled', false);
}
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
});
}
}
But it is not stable.First the message and the button are disabled in the first couples of tried but if I continue to test it by re-enter the code that exist and the code that does not exist the button disabled however the error message is not showing under the input box.
Here is my html code :
<div class = "row" style = "margin-top:15px;">
<div class = "col-md-12">
<div class = "row">
<div class = "col-md-5 text-right" style = "font-weight: bold"><span class="placeholder">Code</span></div>
<div class = "col-md-7">
<div class="form-group">
<input style = "width: 50%"type="text" class="form-control" onkeyup="validateCode()" id="code" placeholder="Enter code" name="code">
<input type="hidden" name="current-code" id = "current-code">
<div class = "row">
<div id = "code-error" class = "col-md-12" style ="color:red"></div>
</div>
</div>
</div>
</div>
</div>
</div>
And here is my controller function for validating the code:
def checkCode() {
def allow
String compareCode = params?.code
def customer = Customer.findByCode(compareCode)
if (customer == null) {
allow = false //not exist
} else if (customer != null) {
allow = true //exist
}
render allow
}
In the file script.js I have a function, which opens pages as a construction from http://www.example.com/#url= and var theUrl, which gets the value of user's input, like http://www.usersurl.com. The code looks like:
if (theUrl != "") {
chrome.tabs.create({
url:
"http://www.example.com/#url=" +
theUrl,
selected: false
});
}
As result new tab with an address http://www.example.com/#url=http://www.usersurl.com is opening.
I have a popup.html too, where user inputs url into form's textfield.
Until now everything works like it should.
Now i want to add to popup.html checkboxes, checking of which will add additional chrome.tabs.create blocks with different URLs. Something like this:
popup.html
<input type="checkbox" id="checkbox1" name="checkbox1" value="checkbox1">
<label for="checkbox1">checkbox1</label><br>
<input type="checkbox" id="checkbox2" name="checkbox2" value="checkbox2">
<label for="checkbox2">checkbox2</label><br>
script.js
if (theUrl != "") && checkbox1="checked" {
chrome.tabs.create({
url:
"http://www.example.com/#url=" +
theUrl,
selected: false
});
}
if (theUrl != "") && checkbox2="checked" {
chrome.tabs.create({
url:
"http://www.anothersite.com/#url=" +
theUrl,
selected: false
});
}
What is the way to do so?
You can verify if a checkbox is checked or not by by using the checked property which will return a boolean based on whether the checkbox is checked or not like this:
const checkbx1 = document.querySelector('#checkbox1');
const checkbx2 = document.querySelector('#checkbox2');
if ((theUrl != "") && checkbox1.checked) {
chrome.tabs.create({
url:
"http://www.example.com/#url=" +
theUrl,
selected: false
});
}
if ((theUrl != "") && checkbox2.checked) {
chrome.tabs.create({
url:
"http://www.anothersite.com/#url=" +
theUrl,
selected: false
});
}
Also, since you have a common condition theUrl != "" in your two if statements, you can use a common if statement for that condition like this:
const checkbx1 = document.querySelector('#checkbox1');
const checkbx2 = document.querySelector('#checkbox2');
if (theUrl != "") {
if (checkbox1.checked) {
chrome.tabs.create({
url:
"http://www.example.com/#url=" + theUrl,
selected: false
});
}
if (checkbox2.checked) {
chrome.tabs.create({
url:
"http://www.example.com/#url=" + theUrl,
selected: false
});
}
}
You have to check for the checked property of the checkbox inputs to determine which ones are selected. However, using an if statement for each case, although correct, can become challenging if the number of checkboxes increases. I would recommend using a loop through all selected checkboxes using a CSS selector, for example:
popup.html
<input type="checkbox" id="checkbox1" name="checkbox" value="http://example.com/#url=">
<label for="checkbox1">Open with example</label><br>
<input type="checkbox" id="checkbox2" name="checkbox" value="http://anothersite.com/#url=">
<label for="checkbox2">Open with anothersite</label><br>
script.js
if (theUrl) {
document.querySelectorAll('[name=checkbox]:checked').forEach(chosen => {
chrome.tabs.create({
url: chosen.value + theUrl,
selected: false
});
});
}
This way you can add as many checkboxes as you want without having to change the code, improving efficiency and maintainability.
<div class="masterform type-selection">
<div class="radio"><span><input type="radio" name="feature_value_6" value="10" required=""></span></div><label>Cool</label>
function ShowLoading() {
var verif = true;
$(".masterform input").each(function() {
if($(this).val() == ""){
verif = false;
}
});
var radio = false;
$(".type-selection div.radio span").each(function() {
if($('.masterform input[type=radio]:checked').size() > 0){
radio = true;
}
});
if(verif == true && radio == true){
window.loading_screen = window.pleaseWait({
blabla }); }
}
i tried everything , the variable send me true but when i use this verification on radio input nothing work. my function work only when i stop the submit on my form by clicking on the cross of my safari navigator !
Everything works fine on chrome but cant make it work on safari
I cleaned up your code. Looks like you just need to use length instead of $.size()
var radio = false;
$(".type-selection div.radio span").each(function() {
if ($('.masterform input[type=radio]:checked').length > 0) {
radio = true;
}
console.log(radio);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="masterform type-selection">
<div class="radio">
<span>
<input type="radio" name="feature_value_6" value="10" required="" checked>
</span>
</div>
<label>Cool</label>
</div>
Try to use the "prop" property of jQuery, like this:
$(".type-selection div.radio span input[type='radio']").each(function(elemIndex, domElement) { //Each radio
if($(domElement).prop('checked')){
radio = true;
}
});
Basically I have a script the function "hola ()" that should return the value of 1 if the radio button value is 1. But for some reason when I try to get the return value in another function i never get it.
The form works perfectly.. the only issue is that it doesnt return the value
Can anyone tell me what i did wrong?? thanks
$(document).ready(function(){
function hola() {
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
return 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
})
}
$("#iForm").submit( function(event){
event.preventDefault();
var user = $("input[name=username]").val();
var password = $("input[name=password]").val();
var dbName = $("input[name=dbName]").val();
var server = $("input[name=server]").val();
$.get("1.php",
{username: user, password: password, dbName: dbName, server: server },
function(data){
if (data == "The table PAGE exists" || data == "The table SUBJECTS exists" || data == "The table USERS exists" ) {
// CALLING THE hola () function and expecting a return
var opt = hola();
$("p").html(data + opt);
}
}
)
})
})
HTML
<!-- Yes or No form -->
<form name="yN" style= "display: none; margin-left: auto; margin-right: auto; width: 6em">
<input type="radio" name="yN" value="1">yes</input>
<input type="radio" name="yN" value="0">no</input>
<button id=1 >click me!</button>
</form>
<!-- Login Form -->
<form id="iForm" style= "display: show">
<label id="username" >Username</label>
<input id="username" name="username"/>
<label id="password">Password</label>
<input id="password" name="password" />
<label id="server" >Server</label>
<input id="server" name="server"/>
<label id="dbName" >dbName</label>
<input id="dbName" name="dbName"/>
<input type="submit" value="submit" />
</form>
<p> </p>
Event handlers cannot return values because they're called asynchronously*.
Your existing hola() function will return immediately and the return statements in the click handlers are only called much later, i.e. when the button is clicked.
My approach would be this, using jQuery deferred objects (jQuery 1.6+):
function hola() {
var def = $.Deferred();
// show the popup confirm form
...
$('input[type=radio]').click(function() {
// determine return value
...
// send it back to anything waiting for it
def.resolve(retval);
});
// return a _promise_ to send back a value some time later
return def.promise();
}
$.get("1.php", { ... }).done(function(data) {
if (...) {
hola().done(function(opt)) { // will be called when the promise is resolved
$("p").html(data + opt);
});
}
});
If you prefer, instead of returning the opt value you could use def.reject() to indicate "non-acceptance" and then use a .fail handler to register a handler to be called for that condition.
You return 1 only in the click function of the radiobutton.
If you want to have a function "hola" that returns 1 if the radiobutton is checked, you simply need something like this:
function hola() {
return $("input:radio[name='yN']:checked").val();
}
hola does not even have a return statement. That's the reason for its not returning anything (more precisely: returning undefined always).
A JavaScript function that does not contain a return statement at all or whose all return statements are within nested functions will never return anything but undefined.
Your are tring to return the value from withing the click callback function. Move the return outside that:
function hola() {
var result;
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
result = 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
});
return result;
}
I just received some really great help today with a prior jQuery problem and figured since my luck was running that maybe I could also get some help with some checkboxes. Can someone please tell me what I am doing wrong?
Thanks!
The checkboxes are correctly echoing the database bool values but when I submit the changed values, an alert() telles me that they are undefined.
else if (item.field == "admCustRptDly" && item.value == "1")
{
$('#admCustRptDly').attr('checked', true);
}
else if (item.field == "admCustRptSumm" && item.value == "1")
{
$('#admCustRptSumm').attr('checked', true);
}
else if (item.field == "admCustRptDtl" && item.value == "1")
{
$('#admCustRptDtl').attr('checked', true);
}
<tr>
<td class="admMarker">Daily<input type="checkbox" id="admCustRptDly" name="admCustRptDly" class="admChkbx"></td>
<td class="admMarker">Summary<input type="checkbox" id="admCustRptSumm" name="admCustRptSumm" class="admChkbx"></td>
<td class="admMarker">Detail<input type="checkbox" id="admCustRptDtl" name="admCustRptDtl" class="admChkbx"></td>
</tr>
$(function() { $('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".admCustBtn").click(function()
{ // validate and process form
// first hide any error messages
$('.error').hide();
var admCustRPSecPhone =
$("input#admCustRPSecPhone").val();
var admCustRptDly =
$("checkbox#admCustRptDly").val();
var admCustRptSumm =
$("checkbox#admCustRptSumm").val();
var admCustRptDtl =
$("checkbox#admCustRptDtl").val();
var dataString =
'admCustID='+ admCustID +
'&admCustRptDly='+ admCustRptDly +
'&admCustRptSumm='+ admCustRptSumm +
'&admCustRptDtl='+ admCustRptDtl;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
alert( "Success! Data Saved");
}
});
return false; }); });
Actually both..
the checkboxes don't have value, so if you try to alert() their values it will lead to "undefined", but if you are facing this on alerting the checkbox itself you are probably doing something wrong.
Setting their values to true, won't lead to anything, as #Soviut said, most properties repeat their names on setting. So your input will get like:
<input type="checkbox" checked="checked" value="1" name="myCheck" />
So, try the above and give us some feedback =´p
Sorry in my case it was the .attr() - works fine for me, even in adobe air.
jQuery('#mycheckbox').attr( "checked" )
Your selectors for the checkboxes are not correct.
var admCustRPSecPhone = $("input#admCustRPSecPhone:checked").val() == 'on';
var admCustRptDly = $("input#admCustRptDly:checked").val() == 'on';
var admCustRptSumm = $("input#admCustRptSumm:checked").val() == 'on';
var admCustRptDtl = $("input#admCustRptDtl:checked").val() == 'on';
You could also use something like:
var admCustRptDly = $("#admCustRptDly:checkbox:checked").val() == 'on';
This will set the values to true/false depending on whether the checkbox is checked or not.
You have no value attribute set on your HTML input element
<input type="checkbox" value="1" id="admCustRptDly" name="admCustRptDly">