I am trying to display an image based on the selection of 4 different radio buttons with 2 different names.
For example the first set of radio buttons should select the product model (two options) and the second set of radio buttons the color (two options).
Here are the radio buttons:
<img src="Rack-BK.jpg" name="formula" id="formula">
<br>
<input type="radio" name="model" value="Rack" id="rack_option">Rack
<input type="radio" name="model" value="NoRack" id="norack_option" >NoRack
<br><br>
<input type="radio" name="color" value="Black" id="black_option" > Black
<input type="radio" name="color" value="Gray" id="gray_option" > Gray
This is what is working but only to select the model but I need the color to be added also.
<script type='text/javascript'>
$(document).ready(function(){
$("input:radio[name=model]").click(function() {
var value = $(this).val();
var image_name;
if(value == 'Rack'){
image_name = "Rack-BK.jpg";
}else{
if(value == 'NoRack'){
image_name = "Without-Rack-BK.jpg";
}
}
$('#formula').attr('src', image_name);
});
});
This is what I tried doing but doesn't work:
<script type='text/javascript'>
$(document).ready(function(){
$("input:radio[name=model]").click(function()
$("input:radio[name=color]").click(function()
{
var value = $(this).val();
var image_name;
if(value == 'Rack')
{
if (value == 'Gray')
{
image_name = "Rack-GY.jpg";
}
image_name = "Rack-BK.jpg";
}
}else{
if(value == 'NoRack')
{
if (value =='Gray'
{
image_name = "Without-Rack-GY.jpg";
}
image_name = "Without-Rack-BK.jpg";
}
}
$('#formula').attr('src', image_name);
});
});
In this case, it appears that a combination of using a switch statement and the 'checked' selector would be of good use.
I would put the event handler on both the radio groups...in this case the input:radio[name=model] and input:radio[name=color] (explicitly defined in case you have any other radio buttons on the page).
Then, inside of the handler get the currently selected value for each group, and do your handling inside of switch statements (better suited for handling a lot of if/else style of checking when you're just looking at the value of the item). This means if you add more options, such as blue, yellow, etc, it will be easier to drop in and handle those cases.
TL;DR: Here's how you could do it:
$("input:radio[name=model], input:radio[name=color]").click(function() { // This handler runs when any of the radio buttons are clicked.
var modelValue = $("input:radio[name=model]:checked").val(); // Find which model radio button is checked.
var colorValue = $("input:radio[name=color]:checked").val(); // Find which color radio button is checked.
var image_name = ""; // Initialize the image name to blank. We will be appending as we go.
switch (modelValue) {
case 'Rack':
image_name += "Rack"; // Rack was selected, so use that value for the first part of the image.
break;
case 'NoRack':
image_name += "Without-Rack"; // No Rack was selected, so use that value for the first part of the image.
break;
default:
image_name += "Rack"; // Make sure there is a default value, or a broken image could occur!
break;
}
switch (colorValue) {
case 'Black':
image_name += "-BK.jpg"; // Black was selected, so use that value for the last part of the image.
break;
case 'Gray':
image_name += "-GY.jpg"; // Gray was selected, so use that value for the last part of the image.
break;
default:
image_name += "-BK.jpg"; // Make sure there is a default value, or a broken image could occur!
break;
}
$('#formula').attr('src', image_name); // Put the image value in the formula image field src.
});
Related
i have 3 check boxes in 3 different pages,i want to check one check box at time means at first all 3 are unchecked and if i checked one check box remaining 2 check boxes should be disable.
each check box value i am storing in 3 different text file using array in the form of 1's and 0's.
now for one page i am reading check box values and based condition trying to disable check box but its not working.
I have Tried this
check box html code:
input type="checkbox" id="cb1" name="check[0]" value="1" />
java script:
<script type="text/javascript">
var cb1 =document.getElementById("cb1");
var cb2 = "<?php echo $cb2_arr[5] ?>" ; //cb2=1 or 0
var cb3 = "<?php echo $cb3_arr[6] ?>"; //cb3=1 or 0
if(cb2 ==1 || cb3 == 1){
cb1.disabled = true;
}else{
cb1.disabled = false;
}
</script>
cb1.disabled = true; for me its not working i kept alert statements above and below it ,only above one is displayed
Please help me how to set disabled property, thanks
try this to disabled and remove disabled,
if ($('#cb3').is(':checked') || $('#cb2').is(':checked')) {
$('#cb1').setAttribute('disabled', true);
}else{
$('#cb1').setAttribute('disabled', false);
}
You need to check input1.value == "", not simply input1 == ""
You also need to fire your method originally, and also run it every time your select lists change value.
Give the function a name
function setCheckState(evt) {
if (input1.value == "" || input2.value == "") {
result.disabled = true;
} else {
result.disabled = false;
}
}
Add event listeners
input1.addEventListener('change', setCheckState);
input2.addEventListener('change', setCheckState);
// Fire the method to get the initial checkbox state set
setCheckState();
Finally, you can reduce your if() statement to a simple assignment...
function setCheckState(evt) {
result.disabled = input1.value == "" || input2.value == "";
}
I have some problems here with javascript.
I want someone to choose an option and a checked box, and if both are checked then other checkboxes should not be able to click.
I had tried to give the function 2 parameters (one is for the option and one for the checkbox).
function bs(id /*,chbxvalue */ )
{
var selectElement = document.getElementById(id);
var selectValue = selectElement.options[selectElement.selectedIndex].value;
//var select2Element = document.getElementById(chbxvalue);
//var selectCHBXval = select2Element.options[select2Element.selectedIndex].value;
if((selectValue == "banana" ) /*&& (document.getElementById("apple").checked == true )*/ )
{
document.getElementById("juice").checked = true;
}
else if(selectValue == "Salad")
{}
}
The thing in the comments doesn't work.
<div id="flavor"><br />
<select id="bss" name="beh" onChange="bs('bss')">
<option value="banana" >banana</option>
<option value="pinapple" >pinapple</option>
</select>
</div>
<div id="divcontainer" class="cont" style="display:block;">
<input type="checkbox" name="app" id="apple" value="appl" />Apples <br />
<input type="checkbox" name="juices" id="juice" value="fj" />Fruitjuice <br />
</div>
I've changed the names here. Has anybody an idea? Sorry, I am not so good with javascript... .
Sounds like you'd like to use simply
document.getElementById("...").disabled=true;
Or if you'd like to disable more checkboxes at once, assign them a class, and use
elements = document.getElementsByClassName("my_class");
for(var i = 0; i < elements.length; ++i)
{elements[i].disabled = "true"; }
I'm not exactly sure if this is what you're after, but it seems like you want some kind of conditional logic. I made a fiddle to illustrate it: https://jsfiddle.net/75uLereo/
var radios = document.myform.type,
select = document.myform.flavor;
for(var i = 0; i < radios.length; i++){
radios[i].addEventListener('change', checkValues);
}
select.addEventListener('change', checkValues);
function checkValues(){
var select = document.myform.flavor,
selectedValue = select.options[select.selectedIndex].value,
radioValue = document.querySelector('input[name = "type"]:checked').value;
if(radioValue !== "undefined"){
switch(selectedValue){
case 'none':
case 'banana':
case 'strawberry':
alert("This is "+selectedValue+" and "+radioValue+". Do some conditional logic with the values!");
break;
default:
break;
}
}
}
This binds a function to change events on the radio buttons and the select and then uses a switch on the different values to do whatever you want it to do.
Updated:
I made another example, with checkboxes and the bool value from the checkboxes if they are selected
https://jsfiddle.net/75uLereo/2/
I have a set of set of checkboxes on which I want to restrict to check maximum of one. If the choice needs to be changed then first checked ones need to be unchecked but maximum limit needs to be one.
Here is the jquery code.
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var checkedReportValues = $('#ReportRow input:checkbox:checked').map(function () {
return this.value;
}).get();
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
alert(checkedReportValues);
})
);
Here, the above code is restricting only one checkbox to be checked but when I am trying to check other, they first are being checked and then unchecked. Where I am doing wrong ?
Here is the dynamically created HTML.
//Add Code to Create CheckBox dynamically by accessing data from Ajax for the application selected above
var Reports = " User, Admin, Detail, Summary";
var arrReportscheckBoxItems = Reports.split(',');
var reportscheckBoxhtml = ''
for (var i = 0; i < arrReportscheckBoxItems.length; i++) {
reportscheckBoxhtml += ' <label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label>';
}
//Add Submit button here
reportscheckBoxhtml += ' <button type="button" id="SubmitReport" class="btn btn-primary">Submit</button>';
$('#ReportRow').html(reportscheckBoxhtml);
Try this: uncheck all other checkboxes except clicked one inside click event handler, like below
$('#ReportRow').on('click', 'input[type="checkbox"]',function(){
$('#ReportRow input[type="checkbox"]').not(this).prop("checked",false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ReportRow">
<input type="checkbox">one
<input type="checkbox">Two
<input type="checkbox">Three
<input type="checkbox">Four
</div>
This line:
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
is saying you want to uncheck the checkbox. It's doing exactly what you tell it to do. Just a comment: Users may be confused since checkboxes are meant to check multiple selections. Radio buttons are designed for being able to select only one option.
you are returning false from the function when there is a checkbox already selected, which is preventing the checkbox selection.
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
Do something like this:
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var curCheckBox = this;
$('#ReportRow').find('input[type="checkbox"]').each(function() {
if(this === curCheckBox)
$(this).attr("checked",true);
else
$(this).attr("checked",false);
});
alert(checkedReportValues);
});
I have a whole bunch of radio buttons formatted in the following way;
<input type="radio" name="Xch" value="XCheese " onclick="incrementIndex()">XCheese<br>
and my incrementIndex() function is simple enough;
var index = 0;
function incrementIndex() {
index += 1;
document.getElementById("demo").innerHTML = ""+index+"";
if ($("#Xch").attr("checked") == true){
index = 10;
}
}
And when a radiobutton is clicked it increments the index, but I want it to increase the index once and only if the button is not checked, the way it is set up, even if the Xch radio button is checked, it keeps increment the index! Please help.
Not sure why you would want to do something like this, but is this what you were trying to do?
<input type="radio" name="ch" value="XCheese " onclick="incrementIndex(this)">XCheese</input><br>
<input type="radio" name="ch" value="YCheese " onclick="incrementIndex(this)">YCheese</input><br>
<input type="radio" name="ch" value="ZCheese " onclick="incrementIndex(this)">ZCheese</input><br>
var index = 0;
var previousValue;
function incrementIndex(e)
{
if(e.checked && e != previousValue) index += 1;
previousValue = e;
alert(index);
}
Here's an example
http://jsfiddle.net/Md8fj/134/
What you're doing isn't exactly clear, but if you want the desired behavior, move the index += 1 inside the if statement that detects if it's already checked. If it's not, then you can increment.
Something like:
var index = 0;
function incrementIndex() {
document.getElementById("demo").innerHTML = ""+index+"";
if ($("#Xch").attr("checked") == true){
index = 10;
}
else {
index += 1;
}
}
You need to use a checkbox instead of a radiobox.
In a radio group, once an input is selected, one input in the group must always remain selected.
In a checkbox group, any number if inputs can be selected or deselected.
Change your HTML to:
<input type="checkbox" name="Xch" value="XCheese " onclick="incrementIndex()">XCheese<br>
And it should work.
I have the following code. I need to see how many checkboxes have been checked in my form and if there are more than four display error and uncheck the last check box,everything is working but how can I uncheck the last check box, thanks
function SetHiddenFieldValue()
{
var checks = document.getElementById('toppings').getElementsByTagName('input');
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var totalChecked = 0;
var itemPrice = 5.99;
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
}
}
And my form is:
<form id="pizza" name="pizza" method="post" action="" class="jcart">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<input type="submit" name="my-add-button" value=" add " />
</form>
I think that I would handle this differently. I'd have a click handler on each checkbox that counts the number of checked boxes (including the current if it is being checked) to see if it is greater than 4. If it is, then I would stop the current event, pop the alert, and reset the state of the checkbox causing the alert. This way it would always popup when clicking the fourth checkbox.
To handle the case where javascript is disabled, you'd need to make sure that your server-side code validates that no more than 4 checkboxes have been checked.
JQuery example:
$(':checkbox').click( function() {
if ($(this).val() == 'on') { // need to count, since we are checking this box
if ($(':checkbox:checked').length > 4) {
alert( "You can only choose up to a maximum of 4 toppings." );
$(this).val('off');
}
}
});
Note if you had other types of checkboxes on the page you could use a class to distinguish them. In that case, the selector becomes (':checkbox.topping') and (':checkbox.topping:checked').
Keep track of the last checked checkbox and set its checked property to false:
// ...
var lastChecked; // Will be used in loop below
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
lastChecked = i; // Store the checkbox as last checked
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
checks[lastChecked].checked = false; // Uncheck the last checked checkbox
} else {
// ...
If you want to uncheck all but the four first ones, do it like this:
// ...
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
if (totalChecked > 4) checks[i].checked = false; // Uncheck checkbox
}
}
Well you'll need to somehow pass into this method which particular checkbox was just checked, and then if the total checked count test fails, then just set that checkbox's .checked property to false.
What if the user checked more than five?
One way to do it is create a javascript function that returns false if more than four checkboxes are checked. In each checkbox, hook the new function like this:
<input type="checkbox" onclick="return myNewFunction(this);">
This will inhibit the user from checking any checkbox that is the fifth one.
Alternatively, you could prevent the user from making an invalid action in the first place, by disabling all the other boxes once four of them are checked, and displaying a message like "Choose up to four of these." This way, you don't let the user do something you know is invalid and then scold them.