How to extract this function to not duplicate code - javascript

This code checks if the checkbox is enabled on site if it is disabled then it disable the textbox.
Function disableTextBox() is a onclick function and the $(function() is used to check the behavior of the checkbox after refreshing the page, I did not use the localstorage for that because sometimes different browsers are used.
How can I write this code better to do not duplicate it?
If the checkbox is checked then the textbox should be enabled, if the checkbox is not checked then the checkbox should be disabled for any input. It saves the checkbox after clicking save button (that is different functionality) not connected with this problem, and when the user back to the page it should check if the checkbox is checked or not and adjust the textfield.
Any ideas how to write it better or something?
$(function()
{
var checkboxField = document.querySelector('#checkbox');
var textBox = document.querySelector('#textBox');
if (checkboxField.checked == true)
{
textBox.disabled = false;
}
else if (checkboxField.checked == false)
{
textBox.disabled = true;
}
});
function disableTextBox()
{
var checkboxField = document.querySelector('#checkbox');
var textBox = document.querySelector('#textBox');
if (checkboxField.checked == false)
{
textBox.disabled = true;
}
else if (checkboxField.checked == true)
{
textBox.disabled = false;
}
}

Call your disableTextBox() function, and instead of the if/else you could use the evaluated boolean result of checkboxField.checked straight ahead:
function disableTextBox() {
var checkboxField = document.querySelector('#checkbox');
var textBox = document.querySelector('#textBox');
textBox.disabled = !checkboxField.checked;
}
jQuery(function( $ ) {
// Do it on DOM ready
disableTextBox();
// and on button click
$('#btnDisableTextBox').on('click', disableTextBox);
// Other DOM ready functions here
});

prefering this way ;)
in this story every thing is boolean
Don't do testing if a boolean is True to déclare a true value for a if...
const
checkboxField = document.querySelector('#checkbox'),
textBox = document.querySelector('#textBox');
checkboxField.onchange = function()
{
textBox.disabled = !checkboxField.checked;
}
<label> modify texy <input type="checkbox" id="checkbox" checked>
<textarea id="textBox"disable> blah blah bla</textarea>

Related

How to make other JQuery run when a separate function runs?

I have the JS code below which filters based on checkboxes being checked or not (I don't think you need to see all the HTML because my question is rather simple/general, I think). All this code works fine, but I added a new function at the bottom (I noted it in the code) that simply has an uncheck all button for one of the sets of checkboxes (because there are like 30 checkboxes and I don't want the user to have to uncheck them all manually).
Anyway, the new script works properly too, except that the overall unrelated script that compares all checkboxes needs to run each time the new Uncheck All/Check All button is clicked.
Is there a simple way to make sure all the other JS runs when this new script is run?
I could be wrong, but I think I just need to somehow trigger this function inside the NEW FUNCTION:
$checkboxes.on('change', function() {
but am not sure how to do that.
ALL JS:
<script>
$(window).load(function(){
Array.prototype.indexOfAny = function(array) {
return this.findIndex(function(v) {
return array.indexOf(v) != -1;
});
}
Array.prototype.containsAny = function(array) {
return this.indexOfAny(array) != -1;
}
function getAllChecked() {
// build a multidimensional array of checked values, organized by type
var values = [];
var $checked = $checkboxes.filter(':checked');
$checked.each(function() {
var $check = $(this);
var type = $check.data('type');
var value = $check.data('value');
if (typeof values[type] !== "object") {
values[type] = [];
}
values[type].push(value);
});
return values;
}
function evaluateReseller($reseller, checkedValues) {
// Evaluate a selected reseller against checked values.
// Determine whether at least one of the reseller's attributes for
// each type is found in the checked values.
var data = $reseller.data();
var found = false;
$.each(data, function(prop, values) {
values = values.split(',').map(function(value) {
return value.trim();
});
found = prop in checkedValues && values.containsAny(checkedValues[prop]);
if (!found) {
return false;
}
});
return found;
}
var $checkboxes = $('[type="checkbox"]');
var $resellers = $('.Row');
$checkboxes.on('change', function() {
// get all checked values.
var checkedValues = getAllChecked();
// compare each resellers attributes to the checked values.
$resellers.each(function(k, reseller) {
var $reseller = $(reseller);
var found = evaluateReseller($reseller, checkedValues);
// if at least one value of each type is checked, show this reseller.
// otherwise, hide it.
if (found) {
$reseller.show();
} else {
$reseller.hide();
}
});
});
//NEW FUNCTION for "UNCHECK ALL" Button
$(function() {
$(document).on('click', '#checkAll', function() {
if ($(this).val() == 'Check All') {
$('input.country').prop('checked', true);
$(this).val('Uncheck All');
} else {
$('input.country').prop('checked', false);
$(this).val('Check All');
}
});
});
});
New button HTML for the new UNCHECK portion:
<input id="checkAll" type="button" value="Uncheck All">
I kept researching and discovered the trigger() function to handle this.
http://api.jquery.com/trigger/

How to disable a text box and clear value with pure javascript when a checkbox is checked

I am having one checkbox and one input text in a row .I want when a user checks the checkbox to diable the text and clear its value.
I tried this one but nothing:
What is wrong?
HTML:
<span style="width: 200px;font-size: 80%;"><input id="chkSendSummary" type="checkbox" name="ctl03$ctl00$ctl00$chkSendSummary" onclick="checkSendSummaryLetter();"></span>
<input name="ctl03$ctl00$ctl00$txtSendSummary" type="text" id="txtSendSummary" class="NormalTextBox" style="width: 170px;">
var chkSendSummaryLetter=document.getElementById('chkSendSummary');
var txtSendSummaryLetter=document.getElementById('txtSendSummary');
if (chkSendSummaryLetter.checked) {
txtSendSummaryLetter.enabled = true;
} else {
txtSendSummaryLetter.value = "";
txtSendSummaryLetter.enabled = false;
}
You've created a custom property enabled, which has no effect on the DOM. Use disabled instead:
if (chkSendSummaryLetter.checked) {
txtSendSummaryLetter.disabled = false;
} else {
txtSendSummaryLetter.value = "";
txtSendSummaryLetter.disabled = true;
}
<script type="text/javascript">
var chkSendSummaryLetter=document.getElementById('chkSendSummary');
var txtSendSummaryLetter=document.getElementById('txtSendSummary');
if (chkSendSummaryLetter.checked) {
txtSendSummaryLetter.value = "";
hide();
}
if
function hide() {
document.getElementById('txtSendSummary').style.display = 'block';
}
</script>
This post already exists: (found in 2 seconds via google)
javascript hide/show element
you could add a parameter within the function to make it have multiple purposes

Javascript or jQuery form validation only for exact action

I have a form with several action buttons, and every button has a different action.
For example, one button is "Save and continue" and another is "Save and finished". I want to validate values from selections on the form, and if the value is equаl to some number, only then can it run the action "finished". I want to validate only for this exact action.
I try this but it did not work:
function OnSubmitForm() {
if(document.pressed == 'SOME ACTION') {
var x=document.forms["FORM NAME"]["INPUT NAME"].value;
var i="";
if (x==null || x!=i) {
alert("You can't do this");
return false;
}
}
else
return true;
}
My idea is to validate only when clicking on the exact action on the form.
Hmm, I have an idea. Why don't you listen for the change event on your <select> element and update the buttons disabled attribute, like so.
$('#mySelectBox').change(function() {
var value = this.value,
disabled = null;
if( value === 1 ) {
disabled = true;
} else if( value === 2 ) {
disabled = false;
}
$('#theButton').prop('disabled', disabled);
});
Or if you want to do it the nerdy way you could do this.
$('#mySelectBox').change(function() {
var value = this.value,
disabled = value === 1 ? true : false;
$('#theButton').prop('disabled', disabled);
});
That should work, hope it helps.

Yui 2.0 Enabling input via multiple radio buttons

I have an application that uses Yui 2.0 and some custom JS. I did not write it originally so I am not really familiar with the Yui JS tools. For this problem I will look at three radio buttons and one text input.
The behavior right now is that when you select radio button s3 you enable text input toEnable.
What I would like to see is that when you select radio button S2 or S3 toEnable is enabled. However using the following example what happens is that once you try and use the NCRS_bind_to_radio method on S2, S3 loses the ability to effect the toEnable input all together.
Anyone have any idea how I can get this input enabled/disabled with both radio buttons?
<ul>
<li><label><input value="MET" type="radio" name="selector" id="s1"> 1</label></li>
<li><label><input value="MET" type="radio" name="selector" id="s2"> 2</label></li>
<li><label><input value="MET" type="radio" name="selector" id="s3"> 3</label></li>
<ul>
<input id="change" type="text" name="toEnable">
//S2 is the new addition here, bind for s3 has been around and works by itself, not with s2
NCRS_bind_to_radio('toEnable', 's2', true, true)
NCRS_bind_to_radio('toEnable', 's3', true, true)
function NCRS_bind_to_checkbox(input, checkbox, required, autofocus){
// Bind an input to a checkbox.
// i.e., the input is disabled until the checkbox is checked
// If "required", then "validate-required" is added/removed as needed.
// If "autofocus", then when the checkbox is checked, this field
// automatically gets focus.
if (typeof checkbox == "string") {
checkbox=document.getElementById(checkbox);
}
if (typeof input == "string") {
input = document.getElementById(input);
}
YAHOO.util.Dom.removeClass(input, 'validate-required');
if (required) {
YAHOO.util.Event.addListener(input, "blur",
NCRS_forms_passive_check_text, input, true)
}
input.disabled = !checkbox.checked;
// Set initial state of "validate-required"
if (checkbox.checked && required) {
YAHOO.util.Dom.addClass(input, 'validate-required');
}
// Add a "click" listener to the checkbox/radio
YAHOO.util.Event.addListener(checkbox, "click", function() {
if (checkbox.checked) {
input.disabled = false;
if (autofocus) {
input.focus();
}
if (required) {
YAHOO.util.Dom.addClass(input, 'validate-required');
}
} else {
NCRS_forms_set_error(input, true)
YAHOO.util.Dom.removeClass(input, 'validate-required');
input.disabled = true;
}
});
// If parent is a "radio" input, also add listeners to sibling radios.
if (checkbox.type == 'radio') {
var item;
for (var i=0; i < checkbox.form[checkbox.name].length; i++) {
item = checkbox.form[checkbox.name][i]
if (item != checkbox) {
// Add a "click" listener to the checkbox/radio
YAHOO.util.Event.addListener(item, "click", function() {
if (!checkbox.checked) {
NCRS_forms_set_error(input, true)
YAHOO.util.Dom.removeClass(input, 'validate-required');
input.disabled = true;
}
})
}
}
}
// Add a "click" listener to the dependent input.
// This was intended to re-enabled a disabled input,
// but doesn't work?
YAHOO.util.Event.addListener(input, "click", function() {
if (!checkbox.checked) {
checkbox.click();
input.focus();
}
});
}
NCRS_bind_to_radio = NCRS_bind_to_checkbox
The problem is that when one radio button is selected the others are deselected. I believe that when you select S3 the input is enabled briefly, then S2's deselect disables the input.
I would modify the method to take an array of inputs, and change this bit of code:
if (!checkbox.checked)
{
NCRS_forms_set_error(input, true)
YAHOO.util.Dom.removeClass(input, 'validate-required');
input.disabled = true;
}
to something like:
var state = true;
for (radio in radioArray)
{
state = state && !radio.checked;
}
if (state)
{
NCRS_forms_set_error(input, true)
YAHOO.util.Dom.removeClass(input, 'validate-required');
input.disabled = true;
}
I've worked with YUI a bit and let me offer you a tip to simplify your code. Instead of doing this:
if (typeof checkbox == "string")
{
checkbox=document.getElementById(checkbox);
}
if (typeof input == "string")
{
input = document.getElementById(input);
}
you can take advantage of YUI's DOM utilities.
var Dom = YAHOO.util.Dom;
checkbox = Dom.get(checkbox);
input = Dom.get(input);
YUI will check whether it's a string or not under the hood and always give you a reference to the element, even if you pass an element into get().
Paul

Javascript: How to make this function working for click effects

I am designing a page where it displays the staff details in following structure :
user can click anywhere in the details box and the checkbox will get selected along with the change in the className of the details <div> box.
The problem i m facing is when i click anywhere in the details box it works fine.. but when i click on checkbox it only changes the className but doesnt make any changes to checkbox.
Also there is one condition, few users are allowed to selected limited staff at a time and few are allowed to select all of them..
I have assigned a myClick() function to the outer <div> box (one with red border)
and the function is :
var selectedCount = 0;
myClick = function(myObj,event)
{
var trgt =(event.srcElement) ? event.srcElement : event.target;
tgName = trgt.tagName;
//following statement gives me correct details element event though i clicked on any child tags
theElem = (tgName == 'DIV') ? trgt : ( (tgName == 'B') ? trgt.parentNode.parentNode : trgt.parentNode);
if(allowed_selection == 'unlimited')
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
}
else if(theElem.className == 'details_hover')
{
theElem.className = 'details_clicked';
if(tgName != 'INPUT') theElem.getElementsByTagName('input')[0].checked = true;
}
}
else
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
selectedCount--;
}
else if(theElem.className == 'details_hover')
{
if(selectedCount == allowed_selection ) return false;
theElem.className = 'details_clicked';
//i think, this is the suspicious area for errors
theElem.getElementsByTagName('input')[0].checked = true;
selectedCount++;
}
}
return false;
};
The problem is these return lines in your function:
return false;
When you connect an event to a form element that performs an action, such as a checkbox or button, returning false will prevent that default action. It stops the event from taking place as it regularly would.
You could try something like this at the top of your function:
var returnValue = (tgName == 'INPUT' && trgt.type == "checkbox") ? true : false;
And then when calling 'return ', use:
return returnValue;
If you return true you allow the checkbox to act as normal and check / uncheck itself.

Categories