I'm using pure JS to try to add a class to a number input when the input has a value. The first part of the JS (which adds the "checked" state) is working, but the portion that adds the class name ("selected") isn't being applied. Any ideas what I'm doing wrong?
This is a combined radio and number input, hence the extra input type.
function select_radio_item_other_button(text_obj, radio_but)
{
if (document.getElementById)
{
el = document.getElementById(radio_but);
if (el.checked)
return;
if (text_obj.value != '')
el.checked = true;
text_obj.className += " selected";
}
}
And the HTML
<div class="other">
<input type="radio" name="radio_21" id="radio_21_22" checked="checked">
<label for="radio_21_22" id="radio_21_22_amt">
<input type="number" style="padding-left:0;" name="radio_21_22_amt" id="radio_21_22_amt" value="" min="0" max="50000000" step="1" onblur="javascript:select_radio_item_other_button(this, 'radio_21_22')">
</label>
</div>
Thanks all - I used a combination of your responses but this is working:
function select_radio_item_other_button(text_obj, radio_but)
{
var el = document.getElementById(radio_but);
if (text_obj.value != '') {
el.checked = true;
text_obj.className += " selected";
}
}
Brackets are a little off, perhaps something like this,
function select_radio_item_other_button(text_obj, radio_but) {
if (document.getElementById) {
el = document.getElementById(radio_but);
if (el.checked) {
return;
}
if (text_obj.value != '') {
el.checked = true;
text_obj.className += " selected";
}
}
}
Also not sure what if (document.getElementById) is supposed to return but what were you trying to accomplish here? It evaluates to true but that seems like an unintended purpose!
Hope this helps!
Related
I have an input tag as follows as part of a form submission.
<input type=“checkbox” id=“allowcheatmode” name=allowCheatMode value=“NO” onchange=“allowCheatModes()”>
And allowCheatModes in a JS function
function allowCheatModes(){
var x = document.getElementById(“allowcheatmode”).checked
if (x) {
document.getElementById(“allowcheatmode”).value = “YES”
} else {
document.getElementById(“allowcheatmode”).value = “NO”
}
But this is not working when I am trying to print the allowcheatmode variable after form submission. What am I doing wrong here?
1) You have included an invalid character “ and ”. You should use " in both HTML and JS.
var x = document.getElementById(“allowcheatmode”).checked
2) There is no function named getElemenetById, instead use getElementById.
3) Add if-else code in the onChange function itself. So that it can trigger when checkbox value changes
NOTE I've added an extra label to just show the current state of the checkbox. You can skip that part.
function allowCheatModes() {
var x = document.getElementById("allowcheatmode").checked
if (x) {
document.querySelector("label").textContent = "YES"
document.getElementById("allowcheatmode").value = "YES"
} else {
document.querySelector("label").textContent = "NO"
document.getElementById("allowcheatmode").value = "NO"
}
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">
<label for="allowcheatmode">NO</label>
Shouldn't it be this:
function allowCheatModes(){
var x = document.getElementById(“allowcheatmode”).checked
if (x) {
document.getElemenetById(“allowcheatmode”).value = “YES”
} else {
document.getElemenetById(“allowcheatmode”).value = “NO”
}
}
Try this
function allowCheatModes(){
var isChecked = document.getElementById("allowcheatmode").checked;
if (isChecked) {
document.getElementById("allowcheatmode").value = "YES";
} else {
document.getElementById("allowcheatmode").value = "NO";
}
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">
The code above will be valid, because you had typo in getElemenetById (should be getElementById, not getElemeNETById). Anyway, you will see nothing in this case, because input with type="checkbox" have no view. You can improve your code adding some div element:
function allowCheatModes(){
var isChecked = document.getElementById("allowcheatmode").checked;
document.getElementById("allowcheatmode-view").innerHTML = isChecked ? "YES" : "NO";
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" onchange="allowCheatModes()">
<div id="allowcheatmode-view">NO</div>
P.S.: "condition ? ifTrue : ifFalse" is ternary operator, the short form of "if"
You did two things wrong
First thing
You put if outside the function, please put if inside the function
function allowCheatModes() {
...
}
Replace with
function allowCheatModes() {
...
if(x){
...
}
}
Second thing
The function name you are using is wrong, you should use getElementById, not getElemenetById
document.getElemenetById
Replace with
document.getElementById
Below is my adjusted snippet, you can refer to it.
Have a good day :)
function allowCheatModes(){
var x = document.getElementById("allowcheatmode").checked;
if (x) {
document.getElementById("allowcheatmode").value = "YES"
} else {
document.getElementById("allowcheatmode").value = "NO"
}
console.log(document.getElementById("allowcheatmode").value);
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">
I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.
The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.
JS
var inp1 = document.getElementById("input1");
inp1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("input2").disabled = true;
}
}
HTML
<input type="text" id="input1">
<input type="text" id="input2">
First, I would use input rather than change. Then, you need to set disabled back to false if the input is blank. Your check for whether it's blank is redundant, you just neither either side of your ||, not both. (I'd also use addEventListener rather than assigning to an .onxyz property, so that it plays nicely with others. :-) )
So:
var inp1 = document.getElementById("input1");
inp1.addEventListener("input", function () {
document.getElementById("input2").disabled = this.value != "";
});
<input type="text" id="input1">
<input type="text" id="input2">
...and then of course if you want it to be mutual, the same for input2.
You can achieve this using focus and blur. Below it is done with JQuery.
$(function() {
$('#input1').focus(function(){
$('#input2').prop('disabled', 'disabled');
}).blur(function(){
$('#input2').prop('disabled', '');
});
$('#input2').focus(function(){
$('#input1').prop('disabled', 'disabled');
}).blur(function(){
$('#input1').prop('disabled', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">
How about using keyup?
Like this;
var inp1 = document.getElementById("input1");
var inp2 = document.getElementById("input2");
inp1.onkeyup = function() { inputValidation(this, inp2); }
inp2.onkeyup = function() { inputValidation(this, inp1); }
function inputValidation(origin, lock) {
var response = hasValue(origin.value);
lock.disabled = response;
}
function hasValue(value) {
return value != "" && value.length > 0;
}
https://jsfiddle.net/8o3wwp6s/
Don't make it harder than it is, this is simple.
var one = document.getElementById('one');
var two = document.getElementById('two');
//checks instantly
var checker = setInterval(function() {
if(two.value !== '') {
one.disabled = true;
} else {
//when its clear, it enabled again
one.disabled = false;
}
if(one.value !== '') {
two.disabled = true
} else {
two.disabled = false;
}
}, 30);
<input id="one">
<input id="two">
I am trying to make a simple calculator. You enter one number, you enter the second one, press PLUS and get alert with an answer. I need to show alert('no data') if you click on PLUS when input fields are not touched.
function num1() {
nm = document.getElementById('nsum1').value;
}
function num2() {
mn = document.getElementById('nsum2').value;
}
function plus() {
sum = +nm + +mn;
if (nm == null || mn == null) {
alert('no data');
} else {
alert(sum);
}
}
<input onchange="num1()" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input onchange="num2()" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
So far I have tried if(sum == undefined)/if(sum == null)/if(sum == false)/if(isNaN(sum))/if(sum == "") and nothing seems to work.
If you haven't touched the input field and get the value, then the result would be ""
You need a condition like
if (nm == "" || mn == "") {
alert('no data');
}
And also you should do operation after validations. You are doing operation and then validating.
Fixed other issues aswell.
function plus() {
mn = document.getElementById('nsum2').value;
nm = document.getElementById('nsum1').value;
if (nm == "" || mn == "") {
alert('no data');
} else {
sum = +nm + +mn;
alert(sum);
}
}
<input id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
You can do it much easier
function plus(num1, num2) {
alert(isNaN(num1) || isNaN(num2) ? 'No data' : num1 + num2);
}
function getNumber(id) {
return parseFloat(document.getElementById(id).value);
}
<input id="nsum1" type="number" placeholder="number" maxlength="6" />
<span onclick="plus(getNumber('nsum1'), getNumber('nsum2'))" id="sum">PLUS</span>
<input id="nsum2" type="number" placeholder="number" maxlength="6" />
I've made some changes to your code to make it more robust. See the inline comments for a description.
Declare variables
It is important to declare your variables, when you don't all the variables you are using will wind up in the global scope. When you Google this you will find many articles like this one: https://gist.github.com/hallettj/64478.
Prevent polluting the global scope. In a small website this may not be much of an issue but when working on larger project or with third party code, this is a must. The link above also explains this to some extend.
Use a button If you want something to be interactive, use an HTML element that was meant for it. The button element should be used, it has all sorts of accessibility features the span doesn't have. For instance, by default it will receive focus when navigating your website with the tab key.
Use descriptive variable names nm and mn may mean something to you now but in 6 months it will be a complete mystery. It also makes the code more readable and thus easier to maintain.
Attach event listeners in JS In general it is a bad idea to assign event listeners through the HTML attribute onXXX="". It is more error prone and a lot more time intensive when you want to change something.
// Wrap your code in a closure to prevent poluting the global scope.
(function() {
// Always declare your variables. These variables are no longer scoped to the window object but are no scoped to the function we're in.
var
valueA = null,
valueB = null;
/**
* To check if your input is a valid number requires a couple of checks.
* It is best to place these into their own method so you're other
* method is more readable.
*/
function isNumber(value) {
if (
// == null checks for undefined and null
value == null ||
value === '' ||
isNaN(value)
) {
return false;
}
return true;
}
function onChangeHandler(event) {
var
// Get the element that dispatched the event.
target = event.target;
// Check if the target has the class we've assigned to the inputs, of not you can ignore the event.
if (!target.classList.contains('js-input')) {
return;
}
// Based on the ID of the target, assign the value to one of the variables for the values.
switch(target.id) {
case 'nsum1':
valueA = parseFloat(target.value);
break;
case 'nsum2':
valueB = parseFloat(target.value);
break;
}
}
function onSumTriggerClicked(event) {
// Check if there are numbers to work with
if (
!isNumber(valueA) ||
!isNumber(valueB)
) {
// If not alert the user
alert('no data');
return;
}
sum = valueA + valueB;
alert(sum);
}
function init() {
var
// Get the calculator element.
calculator = document.getElementById('calculator'),
// Get the button to sum up the value.
sumButton = document.getElementById('sum-trigger');
// Add an event listener for the change event.
calculator.addEventListener('change', onChangeHandler);
// Add an event listener for the click event.
sumButton.addEventListener('click', onSumTriggerClicked);
}
// Call the init method.
init();
})();
<div id="calculator">
<input class="js-input" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<button type="button" id="sum-trigger" id="sum">PLUS</button>
<input class="js-input" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
</div>
Try to track it via Inspector, maybe log the values of nm and mn before anything else and correct your condition accordingly(as the sample).
function plus() {
console.log(nm);
sum = +nm + +mn;
if (nm == null || mn == null) {
alert('no data');
}
It will most likely just be blank. So in this case you can modify your condition into:
if (nm === '' || mn === '') {...}
Hope it will help
Please use this as reference.
I've fixed your code.
if ( num1 === '' && num2 === '' ) {
alert('no data');
} else {
alert( parseInt(num1) + parseInt(num2) );
}
I have a bunch of checkboxes, radio buttons, and text fields on my page. They all have '_boom' appended to the end of the id. I want to detect if any one of these inputs is not its original value, and if so, apply CSS to a button called 'save' on the page. Then, if the user reverts any changes they made and all inputs have their original values, I want to undo the CSS.
I've gotten close with the code below. But let's say I check 3 checkboxes. Upon checking the 1st box, the CSS changes. Good! I check the 2nd and 3rd boxes. The CSS stays the same. Good! But then I uncheck ONE of the boxes, and the CSS reverts. Bad! The CSS should only revert if I undo every change.
$('[id*="_boom"]').change(function() {
var sType = $(this).prop('type'); //get the type of attribute we're dealing with
if( sType === "checkbox" || sType === "radio" ){ //checkbox or radio type
var originalCheckedState = $(this).prop("defaultChecked");
var currentCheckedState = $(this).prop("checked");
if(currentCheckedState !== originalCheckedState){
$("a#save").css("color","#CCCCCC");
}
else {
$("a#save").css("color","black");
}
}
if( sType === "text" ){ //text type
var originalValue = $(this).prop("defaultValue");
var currentValue = $(this).val();
if(currentValue !== originalValue){
$("a#save").css("color","#CCCCCC");
}
else {
$("a#save").css("color","black");
}
}
});
#save {
color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="check_boom" />
<input type="checkbox" id="check1_boom" />
<input type="checkbox" id="check2_boom" />
<input type="radio" id="radio_boom" />
<input type="text" defaultValue="test" id="text_boom" />
<input type="text" defaultValue="test" id="text2_boom" />
Save
There are many possible improvements in your code to make it cleaner and standardized. Things like instead of relying on id you should consider class attribute and all... but I will not revamp your code. Here's the solution to your existing code.
The idea is loop through all the form elements and if atleast one of the elements is different than its default value then set the flag and come out of the loop.
At the end, check for that flag and set the css accordingly.
For this, I have enclosed your elements into a form form1.
$("#form1 :input").change(function() {
var changed = false;
formElems = $("#form1 :input");
for(i=0;i<formElems.length; i++){
var sType = $(formElems[i]).prop("type");
if(sType === "checkbox" || sType === "radio"){
if($(formElems[i]).prop("defaultChecked") !== $(formElems[i]).prop("checked")){
changed = true;
break;
}
}else if(sType === "text"){
if($(formElems[i]).prop("defaultValue") !== $(formElems[i]).val()){
changed = true;
break;
}
}
}
if(changed){
$("a#save").css("color","#CCCCCC");
}else{
$("a#save").css("color","black");
}
});
And here is your form
<form id="form1">
<input type="checkbox" id="check_boom" />
<input type="checkbox" id="check1_boom" />
<input type="checkbox" id="check2_boom" />
<input type="radio" id="radio_boom" />
<input type="text" defaultValue="test" id="text_boom" />
<input type="text" defaultValue="test" id="text2_boom" />
Save
</form>
The problem is, when one of them change to its original value, it doesn't mean there is no change.
So, in your else code block, you should check all the inputs, if all of them are the original values, remove the 'save' class from the button, otherwise, keep it.
var isChanged = function ($element) {
var sType = $element.prop('type');
if (sType === "checkbox" || sType === "radio") {
var originalCheckedState = $element.prop("defaultChecked");
var currentCheckedState = $element.prop("checked");
if (currentCheckedState !== originalCheckedState) {
return true;
} else {
return false;
}
} else if( sType === "text" ) {
var originalValue = $element.prop("defaultValue");
var currentValue = $element.val();
if (currentValue !== originalValue) {
return true;
} else {
return false;
}
}
};
var $inputs = $('[id*="_boom"]');
var isAnyChanged = function () {
$inputs.each(function () {
if (isChanged($(this))) {
return true;
}
});
return false;
};
$inputs.change(function () {
if (isChanged($(this))) {
$("a#save").css("color","#CCCCCC");
} else if (!isAnyChanged()) {
$("a#save").css("color","black");
}
});
I know it is very simple.But Still it is not working.I am multiplying a input number with a fixed number,but is not showing the expected result.it always shows the Error message "Please enter some value" even i enter some integer e.g. 6.
This is Html Code.
<input type="text" class="cc" id="getdata" />
<div id="result"> <input type="text" id="show" /></div>
<input type="button" value="calculate" id="calculate" />
This is JQuery Code.
$(document).ready(function () {
$("#calculate").click(function () {
if ($("#input").val() != '' && $("#input").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#input").val()) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
});
Any help will be highly appreciated.
Can anyone tell me please how to concatenate all clicked values of different buttons in a textbox?I want to show previous and current clicked value of button in a textbox.
Thank you.
Do you not mean #getdata? Where is #input?
Replace ("#input") with ("#getdata") in your code.
Check out this fiddle.
$(document).ready(function () {
$("#calculate").click(function () {
if ($("#getdata").val() != '' && $("#getdata").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#getdata").val()) * 5);
} else {
$("#result").html("Please enter some value");
}
});
});
You have no input whose id is "input". The jquery selector #somestring is looking for an element whose id is somestring.
Replace ("#input") by ("#getdata") in your code.
There is no field with the ID input in the HTML you posted, yet your jQuery is looking for one. Perhaps you meant $('#show')
With jQuery issues, ALWAYS suspect the selector before even wondering what else might be wrong. Confirm it actually finds the elements you think it does - never assume.
console.log($('#input').length); //0
if ($("#input").val() != '' && $("#input").val() != undefined) {
You dont have any field anywhere in your markup with the id input!
I think you intended all the instances of #input in that script to be #getdata, but you should also only read its value once into a variable and use that:
$("#calculate").click(function () {
var val = $('#getdata').val();
if (val != '' && val != undefined) {
$("#result").html("total value is::" + parseInt(val) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
Live example: http://jsfiddle.net/82pf4/
$(document).ready(function () {
$("#calculate").click(function () {
if ($("#getdata").val() != '' && $("#getdata").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#getdata").val()) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
});
Checkout this Fiddle
I think that is what you want.
<input type="text" class="cc" id="getdata" />
<input type="button" value="calculate" id="calculate" />
<div id="result"></div>
<script>
$("#calculate").click(calculate);
$("#getdata").keypress(function(ev){
if(ev.keyCode == 13)
calculate();
});
function calculate()
{
var $getData = $("#getdata");
var $result= $("#result");
if ($getData .val() != '' && $getData .val() != undefined && !isNaN($getData .val()))
{
$result.append((parseInt($getData .val()) * 5) + "<p>");
}
else
{
$result.append("Please enter some value<p>");
}
$getData .val("").focus();
}
</script>