How to disable/enable multiple upload buttons with multiple checkboxes - javascript

I am a beginner and am having trouble making my code work. I want to enable/disable a file upload button by clicking a check box. the code works fine when I have only 1 upload button and one check box but it does not when I have more then one. Can anyone please help?
this is JSFiddle preview .
html code
<label>
<input type="checkbox" id="confirm">
</label>
<input type="file" class="style5" id="abstract" name="abstract" disabled onchange="ValidateSingleInput(this);"/>
<br>
<label>
<input type="checkbox" id="confirmp">
</label>
<input type="file" class="style5" id="poster" name="poster" disabled onchange="ValidateSingleInput(this);"/>
<span class="style5"><br>
<label>
<input type="checkbox" id="confirmr">
</label>
<input type="file" class="style5" id="resume" name="resume" disabled onchange="ValidateSingleInput(this);" />
<span class="style5">
javascript code
window.onload = function() {
var checker = document.getElementById('confirm');
var sbm = document.getElementById('abstract');
checker.onchange = function () {
if(this.checked) {
sbm.disabled = false;
}
else {
sbm.disabled = true;
}
};
};
window.onload = function() {
var checker = document.getElementById('confirmp');
var sbm = document.getElementById('poster');
checker.onchange = function () {
if(this.checked) {
sbm.disabled = false;
}
else {
sbm.disabled = true;
}
};
};
window.onload = function() {
var checker = document.getElementById('confirmr');
var sbm = document.getElementById('resume');
checker.onchange = function () {
if(this.checked) {
sbm.disabled = false;
}
else {
sbm.disabled = true;
}
};
};

You have many window.onload so only the last one is active by the end of the script. One window.onload is enough and then you can run all your functions together. Try this updated demo.
window.onload = function() {
var checker = document.getElementById('confirm');
var sbm_abstract = document.getElementById('abstract');
var checkerp = document.getElementById('confirmp');
var sbm_poster = document.getElementById('poster');
var checkerr = document.getElementById('confirmr');
var sbm_resume = document.getElementById('resume');
checker.onchange = function () {
if(this.checked) {
sbm_abstract.disabled = false;
}
else {
sbm_abstract.disabled = true;
}
} ;
checkerp.onchange = function () {
if(this.checked) {
sbm_poster.disabled = false;
}
else {
sbm_poster.disabled = true;
}
};
checkerr.onchange = function () {
if(this.checked) {
sbm_resume.disabled = false;
}
else {
sbm_resume.disabled = true;
}
};
};
I renamed the variables to not override each other and i initialize all your functions in one window.onload event.

Whenever you write a new window.onload = function() { ... }; you are overwriting the previous function that was going to be executed when the window loads, and that's why only the last check box works.
So, to solve the problem, make sure you put your code inside the same onload.
This should work:
window.onload = function() {
var checker = document.getElementById('confirm');
var sbm = document.getElementById('abstract');
checker.onchange = function () {
if(this.checked) {
sbm.disabled = false;
}
else {
sbm.disabled = true;
}
};
var checkerp = document.getElementById('confirmp');
var sbmp = document.getElementById('poster');
checkerp.onchange = function () {
if(this.checked) {
sbmp.disabled = false;
}
else {
sbmp.disabled = true;
}
};
var checkerr = document.getElementById('confirmr');
var sbmr = document.getElementById('resume');
checkerr.onchange = function () {
if(this.checked) {
sbmr.disabled = false;
}
else {
sbmr.disabled = true;
}
};
};

You only need one window.onload.
Try this:
window.onload = function () {
var checker = document.getElementById('confirm'),
sbm = document.getElementById('abstract'),
checker2 = document.getElementById('confirmp'),
sbm2 = document.getElementById('poster'),
checker3 = document.getElementById('confirmr'),
sbm3 = document.getElementById('resume');
checker.onchange = function () {
enableDisable(checker, sbm);
};
checker2.onchange = function () {
enableDisable(checker2, sbm2);
};
checker3.onchange = function () {
enableDisable(checker3, sbm3);
};
function enableDisable(target, btn) {
btn.disabled = target.checked ? false : true;
};
};
Updated fiddle

Related

How to trigger a function with multiple Event Handler (change)

I would like to add the condition, that the function is only triggered if both
addEventListener('change', SwitchG) Events are True (=both have changed).
The code which I use currently activates the function already when one of the two has changed.
var hallo = document.getElementById("S131_01");
var hallo1 = document.getElementById("S130_01");
hallo.addEventListener('change', SwitchG);
hallo1.addEventListener('change', SwitchG);
function SwitchG () {
var test1 = document.getElementById("submit");
test1.classList.add("css");
}
You need another variable, which checks if both have been changed and only executes the handler function if both changes already happened:
var hallo = document.getElementById("S131_01");
var hallo1 = document.getElementById("S130_01");
var countChanges = 0; // <-- this tracks changes
hallo.addEventListener('change', SwitchG);
hallo1.addEventListener('change', SwitchG);
function SwitchG () {
countChanges += 1; // <-- count up
if (countChanges >= 2) {
countChanges = 0; // <-- reset (if needed)
var test1 = document.getElementById("submit");
test1.classList.add("css");
}
}
A more robust implementation however, also tracks the elements which changed and ensures a repeating change event from a single element won't succeed to run the handler.
For example with this utility:
function ChangedCounter (minChanges) {
var elements = new Set();
return {
changed(element) {
elements.add(element);
},
clear() {
elements.clear();
},
isReady() {
return elements.size >= minChanges;
}
};
}
You'd write it like this:
var hallo = document.getElementById("S131_01");
var hallo1 = document.getElementById("S130_01");
var countChanges = ChangedCounter(2);
hallo.addEventListener('change', SwitchG);
hallo1.addEventListener('change', SwitchG);
function SwitchG (e) {
countChanges.changed(e.target);
if (countChanges.isReady()) {
countChanges.clear();
var test1 = document.getElementById("submit");
test1.classList.add("css");
}
}
You could create a "state" to store when the both has changed. I've created two variables, halloState and hallo1State. The snippet below shows how it could be done:
var hallo = document.getElementById("S131_01");
var hallo1 = document.getElementById("S130_01");
var halloState = false;
var hallo1State = false;
hallo.addEventListener('change', SwitchG);
hallo1.addEventListener('change', SwitchG);
function SwitchG (e) {
if(e.target.id === "S131_01") halloState = true;
else if(e.target.id === "S130_01") hallo1State = true;
if(halloState && hallo1State){
var test1 = document.getElementById("submit");
test1.classList.add("css");
}
}
.css {
background-color:red;
}
<input id="S131_01" type="text"/>
<input id="S130_01" type="text"/>
<button id="submit">Submit</button>

Why my focus() method in JS can not be handled as a onfocus event?

Dom:
<input id="bankCardInput" type="text" onfocus="console.log('inputBox is focused');" v-model="AcctNo" v-change="CardBinQry2()" v-blur="CardBinQry()" maxlength="19" style="width: 70%;">
JS:
$scope.CardBinQry2 = function () {
if (!$scope.AcctNo) {
return;
}
var params = {
"AcctNo": $scope.AcctNo
};
if ($scope.AcctNo.length < 16) {
$scope.BankExist = false;
$scope.BankName = '';
return;
}
$remote.post("BankAmericardQuery.do", params, function (data) {
if (data.resultMap.BankName.indexOf('银行') > -1) {
$scope.BankName = data.resultMap.BankName;
$scope.BankExist = true;
}
setTimeout(function () {
var input = document.getElementById('bankCardInput');
input.focus();
},1000)
},function (error) {
if (error.jsonError[0]._exceptionMessageCode == "not.supported.by.the.bank.card")
$scope.BankName = "卡不支持";
})
};
everytime,the CardBinQry2() method run succeed,i want to see the log 'inputBox is focused',but it didn't.Does anyone tell me why?
You can make it a function
setTimeout(function () {
callback()
},1000)
function callback() {
var input = document.getElementById('bankCardInput');
input.focus();
}

Angular input[type="checkbox"] doesn't getting checked in view though its value is true in scope

When I click "Cancel" in modal window, checkbox is unchecked, but it has to be checked (scope.enabledLogin has true after "Cancel" button is pressed and modal window is dismissed). Why?
Jade:
.checkbox(ng-show="showEnabledLogin", ng-class="{'disabled': (!email.length || userForm.email.$error.email)}")
label(for="enabledLogin")
input(ng-show="showEnabledLogin", type="checkbox", id="enabledLogin", name="enabledLogin", ng-model="enabledLogin", ng-disabled="(!email.length || userForm.email.$error.email)", ng-change="showEnabledLoginModal()")
span Player login enabled
JS:
scope.isEnabledLoginManuallyUnchecked = false;
function checkIfEnabledLoginManuallyUnchecked() {
if(scope.isEnabledLoginManuallyUnchecked) {
scope.showEnabledLogin = false;
scope.showInviteLogin = true;
scope.enabledLogin = false;
} else {
scope.showEnabledLogin = true;
scope.showInviteLogin = false;
scope.enabledLogin = true;
}
}
var enabledLoginModal,
modalScope;
var isOpened = false;
scope.showEnabledLoginModal = function () {
if (isOpened) return;
if ((scope.email.length || scope.userForm.email.$error.email)) {
if (scope.enabledLogin) {
debugger;
var child = scope.$new();
var extension = {
cancel: function (e) {
scope.isEnabledLoginManuallyUnchecked = false;
checkIfEnabledLoginManuallyUnchecked();
enabledLoginModal.dismiss(e);
isOpened = false;
},
modal: {
title: 'Please confirm'
}
};
modalScope = angular.extend(child, extension);
var modalOptions = {backdrop: 'static', templateUrl: 'app/player/edit/show-enabled-login-modal.html'};
enabledLoginModal = Modal.custom(modalOptions, modalScope, 'modal-danger');
isOpened = true;
enabledLoginModal.result.then(function (result) {
});
}
}
}
Please find this in your above code and there
cancel: function (e) {
scope.isEnabledLoginManuallyUnchecked = false;
checkIfEnabledLoginManuallyUnchecked();
enabledLoginModal.dismiss(e);
isOpened = false;
},
This will execute once your click on the modal's cancel button and then you set
scope.isEnabledLoginManuallyUnchecked = false;
that is reason it i will get unchecked also
because you called
enabledLoginModal.dismiss(e);
isOpened = false;
these lines your modal closing when you click on cancel . if I am not clear please create fiddle so can research more.
khajaamin

Checkbox enable/disable and check/uncheck and also button text change with a single button click

I have a button and the button can have two labels - Activate and Deactivate. If I click on the button, then the button labels interchange, i.e. if I click on the button and the current text is Activate, then the text is switched to Deactivate and vice versa. I want to do two more things at a time on this button click -
I have a checkbox named IsMandatory. When I click on the button, if it changes from Activate to Deactivate, then the IsMandatory checkbox becomes disabled and vice versa.
Simultaneously, if the Ismandatory checkbox becomes disabled, it will be unchecked. If the checkbox becomes enabled, it becomes checked.
How can I achieve this???
So far I have done this:
<input type="hidden" id="stat" data-bind="value:IsActive" />
<input type="button" id="butt" onclick="change();" />
<input type="hidden" id="stat2" data-bind="value: IsMandatory" />
<input type="checkbox" id="chckbox" data-bind="checked: IsMandatory" />
<script type="text/javascript">
$(function () {
var stat = document.getElementById("stat").value;
var stat2 = document.getElementById("stat2").value;
//alert(stat);
if (stat == 1) {
document.getElementById("butt").value = "Activate";
document.getElementById("chckbox").disabled = false;
document.getElementById("chckbox").checked = true;
stat2 = 1;
}
else {
document.getElementById("butt").value = "Deactivate";
document.getElementById("chckbox").disabled = true;
document.getElementById("chckbox").checked = false;
stat2 = 0;
}
//if (stat2 == 1)
//{
// document.getElementById("chckbox").checked = false;
//}
//else
//{
// document.getElementById("chckbox").disabled = true;
//}
});
function activeStatus(IsActive) {
//alert(ActiveStatus);
if (IsActive == 1) {
//document.getElementById("chckbox").disabled = false;
return "Activate";
}
else {
//document.getElementById("chckbox").disabled = true;
return "Deactivate";
}
}
function change() {
var butt = document.getElementById("butt").value;
if (butt == 'Deactivate') {
document.getElementById("butt").value = "Activate";
document.getElementById("chckbox").disabled = false;
document.getElementById("chckbox").checked = true;
document.getElementById("stat").value = 1;
document.getElementById("stat2").value = 1;
}
else {
document.getElementById("butt").value = "Deactivate";
document.getElementById("chckbox").disabled = true;
document.getElementById("chckbox").checked = false;
document.getElementById("stat").value = 0;
document.getElementById("stat2").value = 0;
}
}
</script>
EDIT-1: Additional JavaScript Code:
var urlInputConfiguration = "/InputConfiguration";
var url = window.location.pathname;
var Id = url.substring(url.lastIndexOf('/') + 1);
$(function () {
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
var InputConfiguration = function (InputConfiguration) {
var self = this;
self.Id = ko.observable(InputConfiguration ? InputConfiguration.Id : 0).extend({ required: true });
self.SectionName = ko.observable(InputConfiguration ? InputConfiguration.SectionName : '');
self.SectionText = ko.observable(InputConfiguration ? InputConfiguration.SectionText : '');
self.IsActive = ko.observable(InputConfiguration ? InputConfiguration.IsActive : 1);
self.IsMandatory = ko.observable(InputConfiguration ? InputConfiguration.IsMandatory : 1);
};
var InputConfigurationCollection = function () {
var self = this;
//if ProfileId is 0, It means Create new Profile
if (Id == 0) {
self.InputConfiguration = ko.observable(new InputConfiguration());
}
else {
$.ajax({
url: urlInputConfiguration + '/GetInputConfigurationById/' + Id,
async: false,
dataType: 'json',
success: function (json) {
self.InputConfiguration = ko.observable(new InputConfiguration(json));
}
});
}
self.InputConfigurationErrors = ko.validation.group(self.InputConfiguration());
self.saveInputConfiguration = function () {
//self.Country = ko.observable(new Country());
var isValid = true;
if (self.InputConfigurationErrors().length != 0) {
self.InputConfigurationErrors.showAllMessages();
isValid = false;
}
// alert(JSON.stringify(ko.toJS(self.Country())));
if (isValid) {
//self.InputConfiguration().IsMandatory = document.getElementById("stat2").value;
self.InputConfiguration().IsActive = document.getElementById("stat").value;
var activevalue = self.InputConfiguration().IsActive;
if (activevalue == 1)
{
document.getElementById("chckbox").disabled = false;
//document.getElementById("chckbox").checked = true;
self.InputConfiguration().IsMandatory = document.getElementById("stat2").value;
}
else
{
document.getElementById("chckbox").disabled = true;
//document.getElementById("chckbox").checked = false;
self.InputConfiguration().IsMandatory = document.getElementById("stat2").value;
}
$.ajax({
type: (Id > 0 ? 'PUT' : 'POST'),
cache: false,
dataType: 'json',
url: urlInputConfiguration + (Id > 0 ? '/UpdateInputConfigurationInformation?id=' + Id : '/SaveInputConfigurationInformation'),
data: JSON.stringify(ko.toJS(self.InputConfiguration())),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
alert("Case Input Configuration saved successfully.");
window.location.href = '/InputConfiguration';
},
error: function (err) {
var err = JSON.parse(err.responseText);
var errors = "";
for (var key in err) {
if (err.hasOwnProperty(key)) {
errors += key.replace("InputConfiguration.", "") + " : " + err[key];
}
}
$("<div></div>").html(errors).dialog({ modal: true, title: JSON.parse(err.responseText).Message, buttons: { "Ok": function () { $(this).dialog("close"); } } }).show();
},
complete: function () {
}
});
}
};
};
var InputConfigurationsViewModel = function () {
var self = this;
var url = "/InputConfiguration/GetAllInputConfiguration";
var refresh = function () {
$.getJSON(url, {}, function (data) {
self.InputConfigurations(data);
});
};
// Public data properties
self.InputConfigurations = ko.observableArray([]);
// Public operations
self.createInputConfiguration = function () {
window.location.href = '/InputConfiguration/InputConfigurationCreateEdit/0';
};
self.editInputConfiguration = function (inputConfiguration) {
//alert(country.CountryID);
window.location.href = '/InputConfiguration/InputConfigurationCreateEdit/' + inputConfiguration.Id;
};
self.removeInputConfiguration = function (inputConfiguration) {
// First remove from the server, then from the UI
if (confirm("Are you sure you want to delete this profile?")) {
var id = customerProfileConfiguration.Id;
$.ajax({ type: "DELETE", url: 'InputConfiguration/DeleteInputConfiguration/' + id })
.done(function () { self.CustomerProfileConfigurations.remove(inputConfiguration); });
}
}
refresh();
};
ko.applyBindings(new InputConfigurationsViewModel(), document.getElementById("inputconfigurationlist"));
ko.applyBindings(new InputConfigurationCollection(), document.getElementById("inputconfiguration_edit"));
});
var clone = (function () {
return function (obj) {
Clone.prototype = obj;
return new Clone()
};
function Clone() { }
}());
I can't bind the value of IsMandatory, although check/uncheck along with enable/disable is working fine when I click the button. Also, while my button text is Activate, IsActive value is bound as 1, and when my button text is Deactivate, IsActive value is bound as 0. When checkbox is checked, IsMandatory value should have been 1, when checkbox is unchecked, IsMAndatory value should have been 0.
Binding had to be used by force, I tried to use knockout but that's not actually helping.
So first of all, when I get the button value, without clicking it, by using document.getElementById and keeping it inside a variable stat, I had to make sure that if stat = 1, then another variable stat2 which has the value from the checkbox becomes 1 as well. Next, when stat2 = 1, checkbox will be checked. Similar thing was done in the else statement when stat = 0. So now stat2 = 0, and checkbox is unchecked.
if (stat == 1)
{
document.getElementById("butt").value = "Activate";
document.getElementById("chckbox").disabled = false;
stat2 = 1;
if (stat2 == 1) {
document.getElementById("chckbox").checked = true;
}
else {
document.getElementById("chckbox").disabled = false;
}
}
else
{
document.getElementById("butt").value = "Deactivate";
document.getElementById("chckbox").disabled = true;
stat2 = 0;
if (stat2 == 0) {
document.getElementById("chckbox").checked = false;
}
else {
document.getElementById("chckbox").disabled = true;
}
}
Next, the change is incorporated inside the function change(). That means when I click the button, then the change() function is called. Inside it, I had to make sure that if Deactivate becomes Activate, then document.getElementById("stat2").value becomes 1 and if 1, then checkbox should be checked. Reverse would happen if we change from Activate to Deactivate.
function change() {
var butt = document.getElementById("butt").value;
if (butt == 'Deactivate')
{
document.getElementById("butt").value = "Activate";
document.getElementById("chckbox").disabled = false;
document.getElementById("stat").value = 1;
document.getElementById("stat2").value = 1;
if ((document.getElementById("stat2").value) == 1)
{
document.getElementById("chckbox").checked = true;
}
else
{
document.getElementById("chckbox").checked = false;
}
}
else
{
document.getElementById("butt").value = "Deactivate";
document.getElementById("chckbox").disabled = true;
document.getElementById("chckbox").checked = false;
document.getElementById("stat").value = 0;
document.getElementById("stat2").value = 0;
if ((document.getElementById("stat2").value) == 0)
{
document.getElementById("chckbox").checked = false;
}
else
{
document.getElementById("chckbox").checked = true;
}
}
}
Finally, I'm force binding this value of the checkbox inside my IsMandatory property, which is inside my js file. IsMandatory property is the property that I declared in the view model for checkbox. IsActive is the property for button. Whenever IsActive is 1, then I enable the checkbox and then I take the value from my checkbox by using document.getElementById. If value of checkbox = 1, then IsMandatory becomes 1, else IsMandatory becomes 0.
self.InputConfiguration().IsActive = document.getElementById("stat").value;
self.InputConfiguration().IsMandatory = document.getElementById("stat2").value;
var activevalue = self.InputConfiguration().IsActive;
var check = self.InputConfiguration().IsMandatory;
if (activevalue == 1)
{
document.getElementById("chckbox").disabled = false;
//document.getElementById("chckbox").checked = true;
check = 1;
if (check == 1) {
self.InputConfiguration().IsMandatory = 1;
}
else
{
self.InputConfiguration().IsMandatory = 0;
}
}
else
{
document.getElementById("chckbox").disabled = true;
check = 0;
//document.getElementById("chckbox").checked = false;
if (check == 0) {
self.InputConfiguration().IsMandatory = 0;
}
else
{
self.InputConfiguration().IsMandatory = 1;
}
}

JavaScript Anonymous Function and Input Params

I am trying to understand how to properly pass parameters to anonymous functions. It seems like my 'this' is not pointing to where I was hoping it would go. What am I doing wrong?
JSfiddle:
http://jsfiddle.net/Chiliyago/NvGs8/3/
function initUTCDate() {
var $date = new Date();
var $dateUTC = new Date($date.getUTCFullYear(), $date.getUTCMonth(), $date.getUTCDate(), $date.getUTCHours(), $date.getUTCMinutes(), $date.getUTCSeconds());
return $dateUTC;
}
$(function () {
var setUTCDateTime = function (timeType) {
var $input = $(this);
var $d = initUTCDate();
if (timeType == "GMT") {
$input.val($d.toGMTString());
} else {
$input.val("false");
}
};
$('input[data-ucw-currDateTime]').each(setUTCDateTime("GMT"));
});
Try using:
$(function () {
var setUTCDateTime = function (timeType) {
return function () {
var $input = $(this);
var $d = initUTCDate();
if (timeType == "GMT") {
$input.val($d.toGMTString());
} else {
$input.val("false");
}
};
};
$('input[data-ucw-currDateTime]').each(setUTCDateTime("GMT"));
});
DEMO: http://jsfiddle.net/NvGs8/4/

Categories