Display random text based on checkbox selection (javascript) - javascript

I'm getting to grips with Javascript and need to do the following:
Have four checkboxes with the text "Red, Blue, Yellow, Green". When the user clicks the button, one of the colours will display randomly as text.
Any suggestions how to do this with Javascript?

I believe this is what you are trying to do:
http://jsfiddle.net/DerekL/QgGwS/
*I am using jQuery here just for explanatory purposes. Convert it to pure JavaScript if you want to.
$("button").click(function(){
$colors = $("input:checked"); //Get all the checkboxes that are checked
if( $colors.length != 0){ //At least 1 checkbox has to be checked
var index = Math.floor(Math.random()*$colors.length); //generate ran. num
$("span").html($colors[index].value); //show the value
}else{
alert("Choose a color!"); //Tell the user to check at least 1 box
}
});
One of the randomly chosen color from the list of the checked boxes will show up as you click on the button.

Related

Click all checkboxes on a webpage with HTML script (quickbooks/Safar)

So I created the following script to select all check boxes on a page
(function(d) {
var input = d.querySelectorAll('input[type="checkbox"]');
var i = input.length;
while (i--) {
input[i].checked = true;
}
})(this.document);
It does work to do that, however when trying it in Quickbooks while it does select all the boxes, the website does not register it as actually being selected (the total cost at the bottom remains the same, its like it superficially checks the boxes, visually only with no actual register). Any help would be great.
EDIT: Maybe simulating a click instead of changing the box values?
The only thing that changes when physically selecting a box is the value posted below changes to true from false
You should do :
input[i].setAttribute("checked", "");
The checked attribute is a boolean attribute, so the standard way to add it to an element is to pass an empty string for value.
https://developer.mozilla.org/fr/docs/Web/API/Element/setAttribute#Exemple

Is there a way to uncheck a checkbox if it's counter equals to 0 with JavaScript or PHP?

help me out on this one if it's possible.
I have a product page and, on this page, people will be able to select a color to remove from the package and select how many items from determined kind they'll buy.
Example: I'm selling blouses and i have'em in 6 colors, red, blue, purple, yellow, orange and green, the customer would be able to choose one between those 6 or none of them and, they must fill some boxes with some infos, like, how many small blouses, or how many large blouses, etc.
But my website will be mainly accessed by old fellas, so, i can't just do my thing and hope for the best like some would, i need to make this site really easy and almost out of the box to use it.
Heres a printscreen of my web page
-> printscreen: http://prntscr.com/ptdyu2
Anyway, i need to uncheck everybox that has a 0 or smaller number in front of it.
Is there a way for doing this?
function(checkbox_validator){
var checkbox0 = document.getElementsByName(tmcp_checkbox_0_0_quantity)
if (checkbox0 != True){
//This is how much i've progressed on this part, only came until this point
}
}
Sure it is possible. I created you a little example. Basically you will add a event listener for change on the input text fields. If the user types a number, or the value will change somehow, the event listener is getting triggered.
Based on the value you will set the specific checkbox checked or unchecked.
var input = document.getElementById('inputItem1');
var checkbox = document.getElementById('checkItem1');
input.addEventListener("input", update);
function update()
{
//Now update the selector
if (input.value > 0 )
{
checkbox.checked = true;
}
else
{
checkbox.checked = false;
}
}
<form>
<input name="input" value="0" id="inputItem1">
<input type="radio" id="checkItem1" name="checkItem1" value="">
</form>

Create a function to hide divs

I want to display tables when a selection is made in a form and a 'Generate Factsheet' button is clicked. I've got a working code where I individually hide other divs when displaying the one I am interested in. Since I have several options in the form (and hence several corresponding divs in which the respective tables are enclosed), the final code appears bulky. I want to write a function to hide other divs whiles displaying the one I am interested in. This is the code I currently have:
var tableDivs = ['tableOPVDiv','tablePneumoDiv','tableRotaDiv'];
var selectedVaccine;
var selectedTableDiv;
function generateFactsheetFunction(){
// Selecting the vaccine chosen from the dropdown
var e = document.getElementById("selectVaccine");
selectedVaccine = e.options[e.selectedIndex].text;
console.log("selectedVaccine: ", selectedVaccine);
if (selectedVaccine=="Rotavirus Vaccine"){
selectedTableDiv='tableRotaDiv';
console.log("rotavirus selected");
hideOtherTables();
} else if (selectedVaccine=="Polio Vaccine"){
console.log("polio selected");
selectedTableDiv='tableOPVDiv';
hideOtherTables();
} else if (selectedVaccine=="Pneumococcal Vaccine"){
console.log("pneumo selected");
selectedTableDiv='tablePneumoDiv';
hideOtherTables();
}
}
function hideOtherTables(){
var testa = tableDivs.indexOf(selectedTableDiv);
console.log("tableDivs[testa]: ", tableDivs[testa]);
console.log("testa: ", testa);
testb = tableDivs[testa];
console.log("testb: ", testb);
document.getElementById(tableDivs[testa]).style.display="block";
/*var newTableDivs=tableDivs.splice(testa);*/
/*for (y=0;y<newTableDivs.length;y++){
document.getElementById(newTableDivs[y]).style.display="none";
}*/
}
The uncommented part works fine. In the commented part, I want to say that for all array elements other than selectedVaccine, I want the display to be:
document.getElementById(tableDivs[testa]).style.display="none";
I cannot splice the data because the selections are repititive (the selections are from a form). What is the way to set the visibility of tableDivs associated with other selections to be none.
Why should you change the display property of each and every division seperately? give a common class name to all the divisions and hide them all at once and then display only the required table.
$(".yourClass").hide();
document.getElementById(tableDivs[testa]).style.display="block";
You will have to use the jQuery Library too.
If you are not familiar with jQuery then use the for loop to hide all the tables first and then display only the required table.
for (y=0;y<TableDivs.length;y++){//you need not create newTableDivs
document.getElementById(TableDivs[y]).style.display="none";
}
document.getElementById(tableDivs[testa]).style.display="block";
i.e you just have to interchange the order of execution. ;)
Cannot read property 'style' of null this means that document.getElementById(tableDivs[y]) return null and can not find this element
try to write
document.getElementById("ElementId")

Make a selecbox(es) required based on another selectbox using jQuery

I have product called initials like below in my test site
http://dev.mommyjewelry.com/initials/sideways-initial-necklace.html
Now if you go that page and select how many gold initials you will more select box appear below based on the selection. So If I select 2 initials I am display below 2 select boxes below where we have to select the letters of the initials
Now I am looking to make these 2 select boxes for instance in this example required. so If we click add to shopping cart button, display a pop up saying that these 2 select boxes are required. and prevent going to the shopping cart.
So again if I select how many gold initials as 3 then the 3 displayed select boxes are the ones I am looking to make in required.
I know when I have a textbox instead of select box I can use the below code
$("#product_form").submit(function(evt) {
var target = $("#yellow-gold").val(); var target1 = $("#white-gold").val();
if(target == "initial-0" && target1=="initial-0"){
alert("You must select either White Gold or Yellow Gold Necklace.");
evt.preventDefault();
}else{
var number_of_charms = $("#yellow-gold").attr("selectedIndex") + 0;
var number_of_gold = $("#white-gold").attr("selectedIndex") + 0;
var fields_not_empty = $(":text[name^=Product_Attribute]:visible[value]").length;
if(number_of_charms > fields_not_empty) {
$(".error").show();
alert("You left one or more required fields empty. Please check your selection above and adjust as needed.");
evt.preventDefault();
}else if(number_of_gold > fields_not_empty) {
$(".error").show();
alert("You left one or more required fields empty. Please check your selection above and adjust as needed.");
evt.preventDefault();
}
}
});
as you can see above from my above code that I am able to display the message when it a text box by using this line
var fields_not_empty = $(":text[name^=Product_Attribute]:visible[value]").length;
but how to use the same in case of a selectbox?
Try this :
$("div[id^='sideways-yellow']:visible select[name^=Product_Attribute] option:selected[value='select-letter']").length
This should get you the number of not selected options for the gold initial(Where the option value is select-letter)
If you need to get the white one, you can just change sideways-yellow to sideways-white
Sorry about the previous answer, I didn't realize I wasn't getting only the visible ones.

How to allow multiple inputs when multiple buttons are selected

I have a jsfiddle application below:
http://jsfiddle.net/ybZvv/5/
If you open the jsfiddle, you will see a top control which contains "Answer" buttons. You will also see some letter buttons, a "True" button, and a "False" button.
The "True" and "False" buttons work perfectly, meaning that if the user clicks on "True" and then clicks on "False", it replaces the text input as you can't have an answer both "True" and "False".
This works for the same for the "Yes" and "No" buttons.
But there is a problem with the letter buttons. If you click on the letter buttons, you realise that you can click on multiple letter buttons which is fine, but the problem is that it replaces the text input for those letters which is incorrect. If multiple letter buttons are selected, then it should display the text inputs for all of those letter buttons, not replace the text input with the latest letter button selected.
I know the code below
_oCurrAnswerContainer.html('');
empties the container DIV, so it removes the inputs before creating a new one.
But I only want that to happen between the "True" and "False" buttons and "Yes" and "No" buttons. If you select mutliple letter buttons, it should not empty the container:
If buttons A, C and E are turned on, then text input A, C and E is shown, if E is then turned off, then text input for E is removed.
I guess you wanna append. Why can't you make the code this way?
_oCurrAnswerContainer.html(_oCurrAnswerContainer.html() + '' + NewContents);
Append to it. I am not sure, as I don't understand the question.
It seems the solution is to continually inspect the selected letters, each time the user makes a selection or deselect a letter.
Example:
<script type='text/javascript'>
var checkboxes = $('form > p > input:checkbox');
// updates the text input with the selected values...
var update = function() {
var values = [];
$('form > p > input:checked').each(function(idx, cb) {
values.push($(this).val());
});
$('#foo').val(values.join(', '));
};
// count the number of selected items...
var count = function() {
var n = $("input:checked").length;
$("div").text([n, 'box selected!'].join(' '));
};
// bind to the checkbox for clicks
// update the input field
// count the number of selected items
$(checkboxes).on('click', function(e) {
update();
count();
});
update();
count();
</script>
See this gist for a working example

Categories

Resources