how to disable text field and combo box in javascript - javascript

I'm having a problem in disabling textbox and combo box by using another combo box here is my javascript so far:
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("bos").disabled = (val == "Military","Civilian") ? true : false;
document.getElementById("afpsn").disabled = (val == "Dependent","Civilian") ? true : false;
};
and here's my html:
<select name="category" size="1" id="category">
<option selected="selected">Choose...</option>
<option value="Civilian">Civilian</option>
<option value="Military">Military</option>
<option value="Dependent">Dependent</option>
</select>
<select name="bos" id="bos" >
<option value="">Branch of Service</option>
<option value="PAF">PAF</option>
<option value="PA">PA</option>
<option value="PN">PN</option>
<option value="TAS">TAS</option>
</select>
<input id = "afpsn" name="afpsn" type="text" id="afpsn" size="38" placeholder="AFPSN" />
it should be whenever I select dependent or civilian the other combo box and text field will be disabled and will be enable when I select military. please help!

This fiddle will be help you. you can edit logic , too.
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
// alert(val);
document.getElementById("bos").disabled = (val === "Military") ? false : true;
document.getElementById("afpsn").disabled = (val === "Military") ? false : true;
document.getElementById("afpsn").disabled = (val === "Dependent" || val === "Civilian" ) ? true : false;
document.getElementById("bos").disabled = (val === "Dependent" || val === "Civilian" ) ? true : false;
};

I dont think there is anything like (val == "Military","Civilian")
You can try this Fiddle

Try below code:
/*Function to check if value is in an array*/
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
/*******************************************/
var s=document.getElementById("elementId");
s.disabled = isInArray(s.value,["Military","Civilian"]); //Function automatically returns "true" or "false" depending on value
Demo Fiddle

Try this instead:
Your condition (comparison with strings) is incorrect.
example
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("bos").disabled = (val === "Military" || val === "Civilian") ? true : false;
document.getElementById("afpsn").disabled = (val === "Dependent" || val === "Civilian") ? true : false;
};
EDIT:
To attach the event on page load (assuming you are not using jQuery), one way is to attach it on pageload like:
function init() {
category.onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("bos").disabled = (val === "Military" || val === "Civilian") ? true : false;
document.getElementById("afpsn").disabled = (val === "Dependent" || val === "Civilian") ? true : false;
};
}
and something like this on your <body>
<body onload="init();">
...
</body>
The reason why the example worked is that jsfiddle.net loads the functions in the js box on load by default. But in your case, you have to do that manually.

Related

Alternative to a lot of if statements jquery

I'm trying to validate my form using jquery before submission. The user needs to fill up the Task accordingly, they cannot submit the form with fill-up Task 2 and missing Task 1. And also the Task cannot be duplicated with other Task. I'm wondering if there any better way to compare all of this, in a simple method.
The Javascript currently I'm doing. Still not complete yet because looking for better ways.
$(function() {
$( "#create_model" ).submit(function( event ) {
if(validate_task()){
alert("Check your task.");
event.preventDefault();
} else {
$("#create_model").submit();
}
});
});
function validate_task() {
if ($('#CatTask2ID').val() !== "" && $('#CatTask2ID').val() === "") {
return "Task 1 is empty"; //return FALSE;
} else if ($('#CatTask3ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "") {
return "Task 1 or 2 is empty"; //return FALSE;
} else if ($('#CatTask4ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask5ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "" || $('#CatTask4ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask5ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "" || $('#CatTask4ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask1ID').val() === $('#CatTask2ID').val() || $('#CatTask1ID').val() === $('#CatTask3ID').val() .......and others........... ) {
return "Duplicates"; //return FALSE;
}
}
First use classes instead of IDs so you can get a collection of all selects easily, then map each select to its value to get an array of values.
Find the index of the first value which is the empty string. If any values after that one are populated, return an error saying that the index of that empty string is empty.
Otherwise, take the populated values (from indices 0 to the index of the first empty string), and check if the size of a Set of those values is equal to the length of the array:
function validate_task() {
const taskValues = [...$('.tasks')].map(task => task.value);
const firstEmptyIndex = taskValues.indexOf('');
if (firstEmptyIndex > 0 && taskValues.slice(firstEmptyIndex).some(val => val)) {
return `Task ${firstEmptyIndex + 1} is empty`;
}
const populatedTasks = taskValues.slice(0, firstEmptyIndex);
if (populatedTasks.length !== new Set(populatedTasks).size) {
return 'Duplicates';
}
// OK
}
Live demo:
document.addEventListener('change', () => console.log(validateTask()));
function validateTask() {
const taskValues = [...$('.tasks')].map(task => task.value);
const firstEmptyIndex = taskValues.indexOf('');
if (firstEmptyIndex !== -1 && taskValues.slice(firstEmptyIndex).some(val => val)) {
return `Task ${firstEmptyIndex + 1} is empty`;
}
const populatedTasks = taskValues.slice(0, firstEmptyIndex);
if (populatedTasks.length !== new Set(populatedTasks).size) {
return 'Duplicates';
}
return 'OK'
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
function validate_task() {
var error_msg = [];
if($('#CatTask1ID').val() === ""){
error_msg.push('1');
}
if($('#CatTask2ID').val() === ""){
error_msg.push('2');
}
if($('#CatTask3ID').val() === ""){
error_msg.push('3');
}
//......
return error_msg;
}
function validate_task_msg() {
var arr = validate_task()
if(arr&& arr.length<=0){
return true;
}else if(arr.length == 10){//more
return "Duplicates";
}else {
var msg = arr.join(',');
return "Task "+ msg + " is empty"
}
}

Textarea resize when field is empty

I have problem with this code
I will create a JS addon to resize textarea when textfield is empty,
i think this code is good but not work for me :(
reason = document.getElementById('reason').value !== "";
causes = document.getElementById('causes').value !== "";
corrections = document.getElementById('corrections').value !== "";
comment = document.getElementById('comment').value !== "";
var disabled = $('form-control').is(':disabled') == true;
if (disabled && reason){
$("#reason").attr("rows","5");
}
var disabled = $('form-control').is(':disabled') == true;
if (disabled && causes){
$("#causes").attr("rows","5");
}
var disabled = $('form-control').is(':disabled') == true;
if (disabled && corrections){
$("#reason").attr("rows","5");
}
var disabled = $('form-control').is(':disabled') == true;
if (disabled && comment){
$("#reason").attr("rows","5");
}
You need to not repeat yourself (DRY)
let anyFilled = $("#reason,#causes,#corrections,#comment").filter(function() {
return this.value != "";
}).length>0;
if ($('form-control').is(':disabled') && anyFilled) {
$("#reason").attr("rows", "5");
}
Why are you redeclaring disabled so many times? especially since its the same expression each time? Just declare it once and make sure you brush up on DRY programming
var reason = $('#reason').val() !== "";
var causes = $('#causes').val() !== "";
var corrections = $('#corrections').val() !== "";
var comment = $('#comment').val() !== "";
var disabled = $('form-control').is(':disabled') == true;
if (disabled) {
if (causes || corrections || comment) {
$("#reason").attr("rows", "5");
}
}

Sum with jquery not working

I have a lot of labels as shown on a page. I want to sum the values and store them in final_cpa.
HTML :
<label class="tmpcpa">32.1</label>
JS :
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).val() != 0) {
final_cpa += parseInt($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
var run = setInterval(calculate_final_cpa, 500);
However final_cpa is always 0 and allfilled remains false.
That because label don't have a value attribute so the .val() function will always return an empty string, you have to use .text() instead to get the text content inside the label element :
if ($(this).val() != 0) {
Should be :
if ($(this).text() != 0) {
NOTE : as Rayon mentioned in the comment below text() will always return string so better to change the zero in condition to string '0'.
Hope this helps.
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).text() != '0') {
final_cpa += parseInt($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>
Check $(this).text() != "" instead of $(this).val() != 0 as You can not use .val() for getting label text. .text() will give you text of label
if ($(this).text() != "" && $(this).text() != "0") {
....
}
First thing, you need to use .text() instead of .val() to get the text inside a label. Also, if you are expecting your result to contain decimal digits, you need to use parseFloat():
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).text() != 0) {
final_cpa += parseFloat($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>
<br />
<label class="tmpcpa">32.1</label>
Change
if ($(this).val() != 0)
to
if (parseInt($(this).text()) != 0)
Beside your code had an error, you should check the content of the table before parsing them. And because you use decimals in your example, you should switch from parseInt to parseFloat too.
And your allfilled varibale makes no sense, because if the last element of .tmpcpa was empty, it will be false again. So i removed it.
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
var content = $(this).text();
final_cpa += IsNumeric(content) ? parseFloat(content) : 0;
});
console.log(final_cpa);
}
Test it with .text instead of val() as label has no value property
Use Unary plus(+)/Number operator instead of parseInt as parseInt will ignore floating point
Use length of lable-elements to test whether all the label has values !== 0
function calculate_final_cpa() {
var final_cpa = 0;
var countOfFilled = 0;
$('.tmpcpa').each(function() {
if ($(this).text() !== '0') {
final_cpa += +($(this).text()) || 0;
++countOfFilled;
}
});
console.log('Total: ' + final_cpa);
console.log('All filled ' + $('.tmpcpa').length === countOfFilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>
<label class="tmpcpa">32.1</label>
<label class="tmpcpa">0</label>

jquery change text once on change function

The problem is that when i change the option it keeps summing, and i would like for it to only sum one time the value of 10.00, and subtract only once if the value is AR .
LIVE LINK: http://jsfiddle.net/A3qLG/1/
JQUERY:
$(document).ready( function() {
$('#country').on('keyup change', function(e){
var subt_value = $('#subt0').text();
if($(this).val() == 'AR' || $(this).val() == ''){
if(subt_value != '0.00' ){$('#subt0').text(parseFloat(subt_value-10).toFixed(2));}
}else{
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
}
});
});
HTML:
<label id="subt0">8.90</label>
<select id="country">
<option value="US">USA</option>
<option value="BR">Brasil</option>
<option value="AR">Argentina</option>
<option value="CU">Cuba</option>
</select>
I would change the HTML to this to store the original value:
<label id="subt0" data-original="8.90">8.90</label>
And then adjust the Javascript to this:
$(document).ready( function() {
$('#country').on('keyup change', function(e){
//Changed the following line to get the original value
var subt_value = $('#subt0').attr('data-original');
//Changed this to say, NOT AR and has a choice per the comments.
if($(this).val() != 'AR' && $(this).val().length > 0) {
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
} else {
//Otherwise put it back to the original value
$('#subt0').text(subt_value);
}
});
});
try this code
$(document).ready( function() {
$('#country').on('keypress change', function(e){
var subt_value = $('#subt0').text();
if($(this).val() == 'AR' || $(this).val() == ''){
if(subt_value != '0.00' ){$('#subt0').text(parseFloat(subt_value-10).toFixed(2));}
}else{
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
}
});
});
You need to remember previous #country select value, and use it when making decision:
$(document).ready(function () {
var prevValue = '';
$('#country').on('keyup change', function (e) {
var newValue = $(this).val();
var subt_value = parseFloat($('#subt0').text());
if ((newValue == 'AR' || newValue == '')) {
if (prevValue != '' && prevValue != 'AR') {
$('#subt0').text((subt_value - 10).toFixed(2));
}
} else {
if (prevValue == 'AR' || prevValue == '') {
$('#subt0').text((subt_value + 10).toFixed(2));
}
}
prevValue = newValue;
});
});
http://jsfiddle.net/A3qLG/5/
Simply remove the onkeyup and onchange event handler functions after they have done their work.
$('#country').off('keyup change');
Jquery provide a .change() specifically for <select>
You want to sum only one time and substract only one time base on the condition of the selected value AR. Therefore you only need to check the selected value if there is change and do the math within the if-else statement. Finally attach the result with .toFixed(2)
var subt_value = $('#subt0').text();
var add_sub = 0, f=10.00;
$('#country').change(function(){
if ($(this).val() != 'AR'){
add_sub = parseFloat(subt_value)+f;
}else{
add_sub = parseFloat(subt_value)-f;
}
$('#subt0').text(add_sub.toFixed(2));
});
JSFiddle Demo

HTML - How can I create an increment/decrement textbox on an HTML page?

How can i create a increment/decrement text box in HTML Page using jquery or Javascript....
and also i want to set maximum and minimum values....
How to i achieve this?
Simple :)
HTML :
<div id="incdec">
<input type="text" value="0" />
<img src="up_arrow.jpeg" id="up" />
<img src="down_arrow.jpeg" id="down" />
</div>
Javascript(jQuery) :
$(document).ready(function(){
$("#up").on('click',function(){
$("#incdec input").val(parseInt($("#incdec input").val())+1);
});
$("#down").on('click',function(){
$("#incdec input").val(parseInt($("#incdec input").val())-1);
});
});
did you try input type="number"?
Just try
<input type="number" name="points" step="1">
that's it.
In the step, you can enter any value you want. And the arrows will move that many steps on clicking.
Have a look here. I have also used it.
numeric-up-down-input-jquery
I think you can use jquery ui spinner . For a demo take a look at the link here
Try this Spinner Control. hope this will help you.
http://www.devcurry.com/2011/09/html-5-number-spinner-control.html
JavaScript (JQuery) of increment and decrement for both ( - and + ) ##
$(document).ready(function () {
$('#cost').w2form ({
name : 'cost',
style : '',
fields : [
{
name : 'amount',
type : 'int'
}
]
});
$("#amount").keydown(function (e) {
var key = e.keyCode;
if (key == 40) {
if ( $(this).val() != "") {
$(this).val();
} else {
$(this).val("0");
w2ui['cost'].record[$(this).attr('name')] = "0";
w2ui['cost'].refresh();
}
}
});
}
HTML
<html>
<form>
<label>Amount</label>
<input type="text" id="amount" name="amount" style= "width: 140px"/>
</form>
</html>
function incerment(selector, maxvalue){
var value = selector.val() != undefined ? parseInt(selector.val()) : 0;
var max_value = maxvalue != undefined ? parseInt(maxvalue) : 100;
if(value >= max_value){
return false;
} else {
selector.val(++value);
}
}
function decrement(selector, minvalue){
var value = selector.val() != undefined ? parseInt(selector.val()) : 0;
var min_value = minvalue != undefined ? parseInt(minvalue) : 1;
if(value <= min_value){
return false;
} else {
selector.val(--value);
}
}
//MAXIMUM/MINIMUM QUANTITY
$('#up').click(function(){
incerment($("#incdec input"));
return false;
});
$('#down').click(function(){
decrement($("#incdec input"));
return false;
});
Start of arrow keyup and keydown by JavaScript (JQuery)
$("#amount").on('keydown', function (event) {
//up-arrow
if (event.which == 38 || event.which == 104) {
$(this).val((parseInt($(this).val()) + 1));
//down-arrow
} else if (event.which == 40 || event.which == 98) {
$(this).val((parseInt($(this).val()) - 1));
}
});
JavaScript
function forKeyUp(value,e){
e = e || window.event;
if (e.keyCode == '38' || e.keyCode == '104') {
if(parseInt(value)<1000){
value=(parseInt(value) + 1);
var id = $(e.target).attr('id');
$("#"+id).val(value);
}
}
else if (e.keyCode == '40' || e.keyCode == '98') {
if(parseInt(value)>0){
value=(parseInt(value) - 1);
var id = $(e.target).attr('id');
$("#"+id).val(value);
}
}}
//Call function
$("#amount")..on('keydown', function (event) {
forKeyUp($(this).val(),event);
});

Categories

Resources