jquery radio buttons not switching? - javascript

I am confused about this code its self explanatory what its supposed to do but it doesn't do it
<input name="property" type="radio" checked value="1" />Station Masters House
<input name="property" type="radio" value="2" />Railway Carriage
<br><br>
<div id="fillin">press</div>
$("#fillin").click(function() {
if ($('input[name=property]').val() == "1")
{
alert($('input[name=property]').val());
} else if ($('input[name=property]').val() == "2") {
alert($('input[name=property]').val());
}
});
example here
http://jsfiddle.net/BFf5H/40/

input[name=property].length === 2 ... therefore, .val() won't work. (.val pulls the value of the first element in the DOM that it finds that matches the requested selector, except in the case of a <select multiple> element.)
Try input[name=property]:checked instead.
$("#fillin").click(function() {
if ($('input[name=property]:checked').val() == "1")
{
alert($('input[name=property]:checked').val());
} else if ($('input[name=property]:checked').val() == "2") {
alert($('input[name=property]:checked').val());
}
});
Better yet, cache the things you need, so you are only hitting the DOM (or in this case, jQuery's cache) once:
$("#fillin").click(function() {
var val = $('input[name=property]:checked').val();
if ( val == "1") {
alert(val);
} else if (val == "2") {
alert(val);
}
});

you should do
if ($('input[name=property]:checked').val() == "1")

Related

jQuery - How do I use AND with Selector?

My code's function is to alert user if the ptype textfield is empty.
$("input[name*='ptype']").each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
However, I need to add another criteria where another field amount is not 0. So that the function get triggered when ptype="" && amount!=0. I'm very new in jQuery, and I'm not sure how to use AND operator in here. I've tried to do some based on other questions but it seems not working.
$("input[name*='ptype'][amount!='0']").each(function() {
$("input[name*='ptype'] , [amount!='0']").each(function() {
What am I missing ?
You can do it with && sign. Code depends on where your amount field is located and what it is. If I guess right it should be something like this:
$("input[name*='ptype']").each(function() {
if ($(this).val() == "" && $(this).parent().find(input[name='amount']).val() != 0) {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
That code $("input[name*='ptype'][amount!='0']").each(function() { is valid. You have to check the CSS selectors list.
The problem maybe in your *= selection. input[name*="ptype"] means Selects every element whose name attribute value contains the substring "ptype".
$('input[name*="ptype"][amount!="0"]').each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
Take a look at this test https://jsfiddle.net/xpvt214o/211871/
« where another field» is the key in question.
So you need a selector to check if a selected element is empty and another element is not zero.
Holà!
Logic problem here.
with $(selector) you can look up for some elements.
There is no AND / OR in selectors for many sets of matching element.
A selector is ONE set of matching elements.
No way this selector can check for an attribute value of another set.
So you have to know your markup and navigate a bit... And take care of variable types.
$("input[name*='ptype']").each(function() {
if ( parseInt( $(this).next("input").val() ) != 0) {
$(this).css({"background-color" : "red"});
alert("Enter Value!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ptype: <input type="text" name="ptype"><br>
amount: <input type="text" name="amount" value="1">
You have to look for another element's value here, from my understanding. So you have to know what is that "other" element and the methods to use may vary a lot depending on your HTML...
You can use this function in your button.
function check(e){
var verror = false;
$("input[name*='ptype']").each(function(index, value) {
var amount = $($("input[name='amount[]']").get(index)).val();
var ptype = $(this).val();
if(ptype.length <= 0 && amount.length > 0 ){
verror = true;
$(this).focus();
return false;
}
});
if(verror){
e.preventDefault();
alert("Enter Value!");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="1"> <br>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="2"> <br>
<button type="button" onclick="check(event)">Click</button>
</form>

Adding a class name to number input when input has value

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!

How can I apply CSS to a link if at least one input is not original, and undo that change if all inputs are original?

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");
}
});

Cannot set the value properly in javascript

I've 6 following radio buttons
<input type="text" id="status" name="status">
<input type="radio" name="orderReceivingKeysPresent" id="orderReceivingKeysPresent_Y" value="1" onclick="checkKeyAndTitle(this);"> Yes
<input type="radio" name="orderReceivingKeysPresent" id="orderReceivingKeysPresent_N" value="0" onclick="checkKeyAndTitle(this);"> No
<input type="radio" name="orderReceivingTitlePresent" id="orderReceivingTitlePresent_Y" value="1" onclick="checkKeyAndTitle(this);"> Yes
<input type="radio" name="orderReceivingTitlePresent" id="orderReceivingTitlePresent_N" value="0" onclick="checkKeyAndTitle(this);"> No
<input type="radio" name="orderReceivingReturnToOwner" id="orderReceivingReturnToOwner_Y" value="1" onclick="hideAndShowReturnToOwner(this); checkKeyAndTitle(this);"> Yes
<input type="radio" name="orderReceivingReturnToOwner" id="orderReceivingReturnToOwner_N" value="0" onclick="hideAndShowReturnToOwner(this); checkKeyAndTitle(this);" checked="checked"> No
No I'm using javascript for assiging values. I've created javascript function but it isn't working properly and I can't figure it out. How to do it?
function checkKeyAndTitle(getObj) {
if(getObj.name == "orderReceivingKeysPresent") {
if(getObj.value == "1") {
$("#status").val('Delivered');
} else {
$("#status").val('Missing Keys');
}
}
else {
if(getObj.value == "1") {
$("#status").val('Delivered');
} else {
$("#status").val('Missing Title');
}
}
}
Now orderReceivingReturnToOwner is checked to no by default.
When I click at orderReceivingKeysPresent to yes and orderReceivingTitlePresent to no then status should be Missing Title and when orderReceivingKeysPresent no and orderReceivingTitlePresent yes status should be Missing Keys and when both are yes status should be Delivered and also check this one to when orderReceivingReturnToOwner yes status should be Return To Owner. Help suggest me how to do it.
$("input[type='radio']").on("click", function () {
var keyRadioVal = $('input:radio[name=orderReceivingKeysPresent]:checked').val();
var titleRadioVal = $('input:radio[name=orderReceivingTitlePresent]:checked').val();
var ownerRadioVal = $('input:radio[name=orderReceivingReturnToOwner]:checked').val();
if (ownerRadioVal == 1) {
$("#status").val('Return To Owner');
} else if (keyRadioVal == 1 && titleRadioVal == 0 && ownerRadioVal == 0) {
$("#status").val('Missing Title');
} else if (titleRadioVal == 1 && keyRadioVal == 0 && ownerRadioVal == 0) {
$("#status").val('Missing Keys');
} else if (titleRadioVal == 1 && keyRadioVal == 1 && ownerRadioVal == 0) {
$("#status").val('Delivered ');
} else {
$("#status").val('Missing Keys');
}
});
what i had done is getting value of each radio button which is selected on selection change of every single radio button and check all 3 case.
rest in all case Missing key will be shown that you can accordingly.

Calculation issue With JQuery

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>

Categories