How to add an IF block with a checkbox - javascript

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.

Related

Make invalid form immediately after loading

I have a simple form written in AngularJS.
I would like to make the form invalid immediately after loading. Unfortunately $scope.myForm.$valid = false; doesn't want work. Do you have any other technique to do it? It is important for me as I want to let user click the button only when he/she choose at least on checkbox. Now you can submit the form always after loading the form.
<form name="myForm" ng-submit="myForm.$valid">
<input type="checkbox" ng-model="obj.first" ng-change="onChange()" /> First <br />
<input type="checkbox" ng-model="obj.second" ng-change="onChange()"/>Second <br />
<input type="checkbox" ng-model="obj.third" ng-change="onChange()"/> Third <br>
<button type="submit" ng-disabled="!myForm.$valid" ng-click="click()">test</button> <br>
</form>
$scope.myForm = {};
$scope.myForm.$valid = false;
$scope.click=function () {
console.log('-------------2', $scope.myForm);
};
$scope.onChange=function () {
console.log('before:', $scope.myForm);
var isValid = false;
angular.forEach($scope.obj, function(value, key) {
if(value == true){
isValid=true;
}
console.log(key + ': ' + value);
});
if(!isValid){
$scope.myForm.$valid = false;
$scope.myForm.$error.checkBoxes = {
isChecked: false
};
}
console.log('after:', $scope.myForm);
}
So this is my final solution, the form in the scope has a function called $setValidity() where we can change the validity state, and notify the form. Refer here, so I check if any of the checkboxes are having true value, then I set the value for one checkbox alone as true, if not then one of the checkboxes with name one is set to $valid = false, thus the entire form will be invalid, please go through my code for the implementation of the solution!
JSFiddle Demo
JS:
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope) {
$scope.onChange = function() {
if ($scope.obj) {
if ($scope.obj.first || $scope.obj.second || $scope.obj.third) {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", true);
} else {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
}
} else {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
}
}
});
Try this in your submit button. hope it works
data-ng-disabled="myForm.$submitted || myForm.$invalid && !myForm.$pristine"

easier way to toggle a radio button with JavaScript/Ajax?

I've set up radio buttons like this:
<hr />
<h2>PhoneyTV Cabana</h2>
<p>
<input type="radio" id="phoneyRadio1" value="0" onclick="toggleParticlePower(phoneyID, phoneyPowerFunction, this.value)" name="led" />Off
<input type="radio" id="phoneyRadio2" value="1" onclick="toggleParticlePower(phoneyID, phoneyPowerFunction, this.value)" name="led" />On
</p>
there must be a simpler way of updating their stat than this:
$.getJSON(myURL, function(data) {
state = (parseInt(data.result) == 1)
if (state) {
$('#phoneyRadio1').attr('checked', false);
$('#phoneyRadio2').attr('checked', true);
} else {
$('#phoneyRadio2').attr('checked', false);
$('#phoneyRadio1').attr('checked', true);
}
});
I tried just making the 'active' button highlighted, but I'm having trouble with that...
What obvious shortcut am I missing?
if (state) {
$('#phoneyRadio1').attr('checked', false);
$('#phoneyRadio2').attr('checked', true);
} else {
$('#phoneyRadio1').attr('checked', true);
$('#phoneyRadio2').attr('checked', false);
}
In the above code, if you observe closely, a simple pattern that value for phoneyRadio1 is always opposite of condition and phoneyRadio2 is same as condition. So it can be reduced to:
$('#phoneyRadio1').attr('checked', !state);
$('#phoneyRadio2').attr('checked', state);
Now, state = (parseInt(data.result) == 1) will make state a global variable(missing var). Secondly, you are converting data.result to int, so since you are matching same type values, you should use === instead of ==.
So it would look like var state = (parseInt(data.result) === 1) or var state = (+(data.result) === 1).
Sample Fiddle
You can try this.
$.getJSON(myURL, function(data) {
state = (parseInt(data.result) == 1)
$('#phoneyRadio1').attr('checked', !state);
$('#phoneyRadio2').attr('checked', state);
});

Can't get the value of #Html.RadioButtonFor using Jquery, checked attribute not changing

Using MVC 5, I have a radio button for a Boolean property on a Razor view, a simple yes or no selection, like so:
<td class="warning">#Html.LabelFor(model => model.HeartCondition)</td>
<td class="info">Yes #Html.RadioButtonFor(model => model.HeartCondition, true, new { #class = "radio" })</td>
<td class="info">No #Html.RadioButtonFor(model => model.HeartCondition, false, new { #class = "radio"})</td>
<a role="button" class="btn btn-primary btnnav" id="SaveParQ">Save & Next</a>
When I pass a true or false value to the view, the corresponding radio button is selected, and has the checked="checked" attribute. I then want to save the value without having to reload the page, which I'm trying to do using jquery, and this is where the problem lies. If I pass a true value to the view, the "yes" radio button is selected and has the checked attribute, but when I click the "no" radio button, the "no" button does get selected, but the checked attribute is still on the "yes" button, and doesn't change to the "no" button, which is what I thought it would've done.
My jquery looks like this:
//Save ParQ
$("body").on("click", "#SaveParQ", function (e) {
preventDefaultAction(e);
var url = GetUrlPath() + "/PreAssessment/SaveParQ";
var parQId = $("#ParQId").val();
var heartCondition = false;
if ($("input[name='heartCondition']:checked").val()) {
heartCondition = true;
}
var viewModel = new ParQViewModel(parQId, heartCondition);
$.ajax({
type: "POST",
cache: false,
url: url,
data: JSON.stringify(viewModel),
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.success === true) {
showFullScreenLoadMask(false);
$("#ParQId").val(result.ParQId);
}
},
error: function (responseText, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
});
I'm not sure if my jquery is right, but if it is, it doesn't register me changing "yes" to "no", because the checked attribute stays on the original element. Can anyone help with the right way to achieve what I'm trying to do?
Remove the following lines of code
var heartCondition = false;
if ($("input[name='heartCondition']:checked").val()) {
heartCondition = true;
}
and replace with
var heartCondition = $("input[name='HeartCondition']:checked").val();
which will set the value to either true or false based on the selected radio button.

Checkbox not getting checked via jquery

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

JQuery submitted values for checkboxes are undefined

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">

Categories