How to make textboxes readonly based on drop down selection? - javascript

I have the following scripts that it puts the data-length and data-width on textbox based on drop down question
My question is how I make the .width and .length textboxes readonly based on dropodown selection as below?
$(document).ready(function() {
$('select.cargo_type').change(function() {
var eur1width = $('select.cargo_type').find(':selected').data('width');
$('.width').val(eur1width);
//make width textbox readonly
var eur1length = $('select.cargo_type').find(':selected').data('length');
$('.length').val(eur1length);
//make length textbox readonly
});
});

You can use prop to set textbox readonly.
$('.width').val(eur1width).prop('readonly', true);
$('.length').val(eur1length).prop('readonly', true);
To remove readonly you can set the readonly property to false;
$('.width').val(eur1width).prop('readonly', false);
$('.length').val(eur1length).prop('readonly', false);
UPDATE
if (eur1width == 'myVal') {
$('.width').val(eur1width).prop('readonly', true);
} else {
$('.width').val(eur1width).prop('readonly', false);
}

Use prop('readonly',true/false); on the element. Like,
if(eur1width == 'checking_val'){
$('.width').val(eur1width).prop('readonly', true);
}else{
$('.width').val(eur1width).prop('readonly', false);
}
OR
To toggle the property
$('.width').val(eur1width).prop('readonly', !$(this).prop('readonly'));

Related

D3 using classed() to add and remove class with checkbox

I am having trouble removing a class that I have added using a checkbox. The checkbox is checked to begin with. When it is unchecked by the user it adds a "hideRect" class with classed('hideRect', true);
this works great BUT when I check the box again the class doesn't go away.
Here is my code:
this.$node.append('input')
.attr('type', 'checkbox')
.attr('checked', true)
.attr('value', 'med')
.on('click', () => this.updateRectLine());
}
private updateRectLine() {
//var rect = this.$node.getElementsByClassName('.MEDICATION');
var cbMed = this.$node.attr("checked");
if (cbMed !== true){
this.$node.selectAll(".MEDICATION").classed('hideRect', true);
}
else if (cbMed == true){
this.$node.selectAll(".MEDICATION").classed('hideRect', false);
}
}
thanks in advance!
You need to update the below function like this
private updateRectLine() {
var cbMed = this.$node.select("input[type='checkbox']").prop("checked");
if (!cbMed)
this.$node.selectAll(".MEDICATION").classed('hideRect', true);
else
this.$node.selectAll(".MEDICATION").classed('hideRect', false);
}
.attr() function only returns the value the checkbox was initialized to, to check for a checkbox's check state, you want to use property checked present on check box elements

How do I retain disabled checkboxes upon postback?

I have this set of javascript codes which allows me to disable/enable checkboxes according to my selection.
The 1st set of codes below allows me to set the default as "Select All" and disables the rest when "Select All" is checked during the 1st page load but not on postback. The reason to not do it in post back is because e.g If a user did not check any checkbox in checkboxlist2, I want to prompt the user the select the check at least one checkbox in checkboxlist 2 but do not want to overwrite the user selection previously on postback with the default "Select All" in checkboxlist1 and checkboxlist2.
$(function () {
if($("#hidden").val() == "")
{
$("#Checkboxlist1 :checkbox").attr('disabled', 'disabled');
$("#Checkboxlist1 :checkbox[value='Select All']").removeAttr('disabled');
$("#Checkboxlist1 :checkbox[value='Select All']").prop("checked", true);
$("#Checkboxlist2 :checkbox").attr('disabled', 'disabled');
$("#Checkboxlist2 :checkbox[value='Select All']").removeAttr('disabled');
$("#Checkboxlist2 :checkbox[value='Select All']").prop("checked", true);
$("#hidden").val("set");
}
});
$(function () {
$("#Checkboxlist2 :checkbox").change(function () {
var ischecked = $(this).is(":checked");
var val = $(this).val();
//alert(val);
if (val == "Select All") {
if (ischecked) {
$("#Checkboxlist2 :checkbox").attr('disabled', 'disabled');
$(this).removeAttr('disabled');
$("#Checkboxlist2 :checkbox").prop("checked", false);
$(this).prop("checked", true);
return;
} else {
$("#Checkboxlist2 :checkbox").removeAttr('disabled');
return;
My question is:
upon postback my check values retains but the checkboxes disabled previously are enabled so how do I retain its whole state upon postback?
I did enabled my checkboxlist enableviewstate = true
I am not sure where you are setting $("#hidden") this value to empty.
but if your checkbox change event is intended to set all checkbox disabled status proper, just call the trigger method on change event right after that event handler.
Something like this.
$("#Checkboxlist2 :checkbox").trigger('change');
like this
$("#Checkboxlist2 :checkbox").change(function () {
var ischecked = $(this).is(":checked");
var val = $(this).val();
//alert(val);
if (val == "Select All") {
if (ischecked) {
$("#Checkboxlist2 :checkbox").attr('disabled', 'disabled');
$(this).removeAttr('disabled');
$("#Checkboxlist2 :checkbox").prop("checked", false);
$(this).prop("checked", true);
return;
} else {
$("#Checkboxlist2 :checkbox").removeAttr('disabled');
return;
}
}
});
$("#Checkboxlist2 :checkbox").trigger('change');
Just try to put a flag in document.ready function..It may work

How to append and remove checkbox values to and from hidden field

I am trying to append selected checkbox values to the hidden field.
But I am only successfull in adding only one checkbox value at this time.
Is there anyway to append selected checkbox values in hidden field.
function CheckBox_Clicked(item) {
if (item.checked == true) {
$('#Chkboxvalue').val($(item).val());
}
}
I don't know if I could use jquery append function here.
Thanks
Please use below javascript
function CallOnEachCheckBoxChangeEvent(){
var selectedCheckBoxesValue = '';
$('#DIVID').find("input:checkbox.CheckBoxClassName:checked").each(function (i, selected) {
if (selectedCheckBoxesValue.length == 0) {
selectedCheckBoxesValue += $(selected).val();
}
else {
selectedCheckBoxesValue += ',' + $(selected).val();
}});
//Set the value of hiddenField selected checkboxes value
$(hiddenFieldValueId).val(selectedCheckBoxesValue);
}
$('#Chkboxvalue').val($('#Chkboxvalue').val()+' '+$(item).val());
There is an easier way to do that.
$('input[type="checkbox"]:checked').map(function() {
return $(this).val();
}).get().join();
Demo : http://jsfiddle.net/codef0rmer/EWsMX/

How can I check if a value is changed on blur event?

Basically I need to check if the value is changed in a textbox on the 'blur' event so that if the value is not changed, I want to cancel the blur event.
If it possible to check it the value is changed by user on the blur event of an input HTML element?
I don't think there is a native way to do this. What I would do is, add a function to the focus event that saves the current value into a variable attached to the element (element.oldValue = element.value). You could check against that value onBLur.
Within the onblur event, you can compare the value against the defaultValue to determine whether a change happened:
<input onblur="if(this.value!=this.defaultValue){alert('changed');}">
The defaultValue will contain the initial value of the object, whereas the value will contain the current value of the object after a change has been made.
References:
value vs defaultValue
You can't cancel the blur event, you need to refocus in a timer. You could either set up a variable onfocus or set a hasChanged variable on the change event. The blur event fires after the change event (unfortunately, for this situation) otherwise you could have just reset the timer in the onchange event.
I'd take an approach similar to this:
(function () {
var hasChanged;
var element = document.getElementById("myInputElement");
element.onchange = function () { hasChanged = true; }
element.onblur = function () {
if (hasChanged) {
alert("You need to change the value");
// blur event can't actually be cancelled so refocus using a timer
window.setTimeout(function () { element.focus(); }, 0);
}
hasChanged = false;
}
})();
Why not just maintaining a custom flag on the input element?
input.addEventListener('change', () => input.hasChanged = true);
input.addEventListener('blur', () => 
{
if (!input.hasChanged) { return; }
input.hasChanged = false;
// Do your stuff
});
https://jsfiddle.net/d7yx63aj
Using Jquery events we can do this logic
Step1 : Declare a variable to compare the value
var lastVal ="";
Step 2: On focus get the last value from form input
$("#validation-form :input").focus(function () {
lastVal = $(this).val();
});
Step3:On blur compare it
$("#validation-form :input").blur(function () {
if (lastVal != $(this).val())
alert("changed");
});
You can use this code:
var Old_Val;
var Input_Field = $('#input');
Input_Field.focus(function(){
Old_Val = Input_Field.val();
});
Input_Field.blur(function(){
var new_input_val = Input_Field.val();
if (new_input_val != Old_Val){
// execute you code here
}
});
I know this is old, but I figured I'd put this in case anyone wants an alternative. This seems ugly (at least to me) but having to deal with the way the browser handles the -1 index is what was the challenge. Yes, I know it can be done better with the jquery.data, but I'm not that familiar with that just yet.
Here is the HTML code:
<select id="selected">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
Here is the javascript code:
var currentIndex; // set up a global variable for current value
$('#selected').on(
{ "focus": function() { // when the select is clicked on
currentIndex = $('#selected').val(); // grab the current selected option and store it
$('#selected').val(-1); // set the select to nothing
}
, "change": function() { // when the select is changed
choice = $('#selected').val(); // grab what (if anything) was selected
this.blur(); // take focus away from the select
//alert(currentIndex);
//setTimeout(function() { alert(choice); }, 0);
}
, "blur": function() { // when the focus is taken from the select (handles when something is changed or not)
//alert(currentIndex);
//alert($('#selected').val());
if ($('#selected').val() == null) { // if nothing has changed (because it is still set to the -1 value, or null)
$('#selected').val(currentIndex); // set the value back to what it originally was (otherwise it will stay at what was newly selected)
} else { // if anything has changed, even if it's the same one as before
if ($('#selected').val() == 2) { // in case you want to do something when a certain option is selected (in my case, option B, or value 2)
alert('I would do something');
}
}
}
});
Something like this. Using Kevin Nadsady's above suggestion of
this.value!=this.defaultValue
I use a shared CSS class on a bunch of inputs then do:
for (var i = 0; i < myInputs.length; i++) {
myInputs[i].addEventListener('blur', function (evt) {
if(this.value!=this.defaultValue){
//value was changed now do your thing
}
});
myInputs[i].addEventListener('focus', function (evt) {
evt.target.setAttribute("value",evt.target.value);
});
}
Even if this is an old post, I thought i'd share a way to do this with simple javascript.
The javascript portion:
<script type="text/javascript">
function HideLabel(txtField){
if(txtField.name=='YOURBOXNAME'){
if(txtField.value=='YOURBOXNAME')
txtField.value = '';
else
txtField.select();
}
}
function ShowLabel(YOURBOXNAME){
if(txtField.name=='YOURBOXNAME'){
if(txtField.value.trim()=='')
txtField.value = 'YOURDEFAULTVALUE';
}
}
</script>
Now the text field in your form:
<input type="text" id="input" name="YOURBOXNAME" value="1" onfocus="HideLabel(this)"
onblur="ShowLabel(this)">
And bewn! No Jquery needed. just simple javascript. cut and paste those bad boys. (remember to put your javascript above the body in your html)
Similar to #Kevin Nadsady's post, the following will work in native JS functions and JQuery listener events. Within the onblur event, you can compare the value against the defaultValue:
$(".saveOnChange").on("blur", function () {
if (this.value != this.defaultValue) {
//Set the default value to the new value
this.defaultValue = this.value;
//todo: save changes
alert("changed");
}
});
The idea is to have a hidden field to keep the old value and whenever the onblur event happens, check the change and update the hidden value with the current text value
string html = "<input type=text id=it" + row["cod"] + "inputDesc value='"
+ row["desc"] + "' onblur =\"if (this.value != document.getElementById('hd" + row["cod"].ToString() +
"inputHiddenDesc').value){ alert('value change'); document.getElementById('hd" + row["cod"].ToString() +
"inputHiddenDesc').value = this.value; }\"> " +
"<input type=hidden id=hd" + row["cod"].ToString() + "inputHiddenDesc value='" + row["desc"] + "'>";

Toggle dropdownlist enable and disable with a button click using Javascript?

I have the following JavaScript to disable a dropdownlist in a ASP.NET page, which gets called when I click a button.
function disableDropDown(DropDownID)
{
document.getElementById(DropDownID).disabled = true;
return false;
}
I wanted to use the same button to toggle between enable and disable for that dropdownlist. How do I do this?
You just have to invert the boolean disabled attribute:
function toggleDisableDropDown(dropDownID) {
var element = document.getElementById(dropDownID); // get the DOM element
if (element) { // element found
element.disabled = !element.disabled; // invert the boolean attribute
}
return false; // prevent default action
}
function toggleDisableDropDown(DropDownID)
{
var sel = document.getElementById(DropDownID);
sel.disabled = !sel.disabled;
return false;
}

Categories

Resources