Change Dropdown value based on checkbox - javascript

I'm a bit stuck and not quite understanding why. I'm working within a pre-existing box that requires us to create a work-around - to simplify the explanation, basically what I need to do is populate a dropdown list with the value of a selected checkbox.
I've gotten the basics of that to work with the following code:
<h4>Select a Date:</h4>
<input type="checkbox" id="session_1" value="1" name="this">Session 1
<br>
<input type="checkbox" id="session_2" value="2" name="this">Session 2
<br>
<input type="checkbox" id="session_3" value="3" name="this">Session 3
<br>
<input type="checkbox" id="session_4" value="4" name="this">Session 4
<br/>
<input type="checkbox" id="session_5" value="5" name="this">Session 5
<br>
<input type="checkbox" id="session_6" value="6" name="this">Session 6
<br>
<br/><br/>
<select id="hidden_select">
<option>-</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
and the jQuery:
$(':checkbox').on('change',function(){
var th = $(this), name = th.prop('name');
if(th.is(':checked')){
$(':checkbox[name="' + name + '"]').not($(this)).prop('checked',false);
}
});
$('input#session_1').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(1)').attr('selected', true);
} else {
$('#hidden_select>option:eq(1)').attr('selected', false);
}
});
$('input#session_2').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(2)').attr('selected', true);
} else {
$('#hidden_select>option:eq(2)').attr('selected', false);
}
});
$('input#session_3').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(3)').attr('selected', true);
} else {
$('#hidden_select>option:eq(3)').attr('selected', false);
}
});
$('input#session_4').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(4)').attr('selected', true);
} else {
$('#hidden_select>option:eq(4)').attr('selected', false);
}
});
$('input#session_5').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(5)').attr('selected', true);
} else {
$('#hidden_select>option:eq(5)').attr('selected', false);
}
});
$('input#session_6').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(6)').attr('selected', true);
} else {
$('#hidden_select>option:eq(6)').attr('selected', false);
}
});
You can see the jsfiddle here.
This works if you were to click one option and be done with it, or click different boxes in sequential order (1-6), but if you change your mind and go back (Select 1, then 4, then go back to one) the dropdown no longer updates.
Any thoughts as to why it stops recognizing the change? Is there a way to get past it?

Your options in your select are staying selected even after you click on a different checkbox. When you set one of the options to selected, make sure you remove the selected attribute from other options:
$('input#session_3').on('change', function () {
if ($(this).is(':checked')) {
//PUT THIS LINE ON EACH OF YOUR HANDLERS
$('#hidden_select>option').attr('selected', false);
$('#hidden_select>option:eq(3)').attr('selected', true);
} else {
$('#hidden_select>option:eq(3)').attr('selected', false);
}
});
Updated fiddle: https://jsfiddle.net/qnd75wmf/5/

Related

Selecting a class of radio button inside a form

I am using jquery to display some forms depending on user input. I have a basic info to fill and then the user select radio buttons that will show one distinct form depending on the input (four radio buttons, 2 questions). The problem is that I don't know how to choose it, I want two distint functions for each question.
My Jquery code (just the idea of what I want):
$(document).ready(function () {
$('form[name="THE_FORM"]'.find('p.ISVM')).click(function () {
if ($(this).attr("value") == "1") {
$('#first').hide();
$('#second').show();
}
if ($(this).attr("value") == "2") {
$('#first').show();
$('#second').hide();
}
});
$('form[name="THE_FORM"]'.find('p.ISVH').click(function () {
if ($(this).attr("value") == "3") {
$('#third').hide();
$('#fourth').show();
}
if ($(this).attr("value") == "4") {
$('#third').show();
$('#fourth').hide();
}
});
});
HTML:
<div id="main">
<form name="The_FORM">
<p class = "ISVH"> <span> Is Virtual host? </span>
<label for="VH"> Yes <input id="VH" type="radio" name="VH" value="3"> </label>
<label for="NVH"> No <input id="NVH" type="radio" name="VH" value="4"> </label> </p>
<p class = "ISVM"> <span> Is Virtual Machine? </span>
<label for="VM"> Yes <input id="VM" type="radio" name="VM" value="1"> </label>
<label for="PM"> No <input id="PM" type="radio" name="VM" value="2"> </label> </p>
...divs first, second, third, fourth here...
</form>
</div>
I tried:
$('form[name="THE_FORM"]'.find('p.ISVM')).click(function () ...
$('form[name="THE_FORM"]: p.ISVM')).click(function () ...
Bit is not working..
What I am doing wrong here? How I write the jquery functions to select the what I want?
$('form[name="THE_FORM"]'.find('p.ISVM')).click(function () ...
should be
$('form[name="THE_FORM"]').find('p.ISVM').click(function () ...
while
$('form[name="THE_FORM"]: p.ISVM')).click(function () ...
should be
$('form[name="THE_FORM"] p.ISVM')).click(function () ...
Also, using name attribute is not as efficient as using an ID:
and then one of these would be my preference:
$('#THE_FORM').find('p.ISVM').click(function () ...
$('#THE_FORM p.ISVM').click(function () ...
or even
$('#THE_FORM').on('click', 'p.ISVM', function () ...
which does something else, but that something else is nice.
Even better, I'd probably disregard click and go directly for change event on inputs.
$(input[name*='VH']).change()
{
var vh= $(input[name*='VH']).val();
if (vh == 1 )
{
$('#first').hide();
$('#second').show();
} else if (vh == 2)
{
$('#first').show();
$('#second').hide();
}
}
$(input[name*='VM']).change(){
var vm = $(input[name*='VM']).val();
if (vm == 1 )
{
$('#third').hide();
$('#fourth').show();
} else if (vh == 2)
{
$('#fourth').hide();
$('#third').show();
}
}

jquery dynamically created checkbox not working properly with function

I wrote a jquery for dynamic generation of check box as well as subtraction operation performed on text box with the value of checked check box. Jquery is working fine with predefined checkbox but not working with dynamically created checkbox. I tried solution like "ON" delegate but still i am struck here my code is like
HTML
<select class="select valid" id="destination" name="destination">
<option value="">Select One</option>
<option value="92">92(11)</option>
<option value="923">923(12)</option>
<option value="9230">9230(12)</option>
<option value="9231">9231(12)</option>
<option value="9232">9232(12)</option>
<option value="9233">9233(12)</option>
<option value="9234">9234(12)</option>
<option value="9235">925(12)</option>
</select>
<label for="port">Ports</label>
<input type="text" id="port" max="128" min="1"/><br><br />
<input type='checkbox' value="5" name='ch1[]' class='checkbox'/>Working Fine
<input type="submit" onsubmit="" value="Save" id="button1" name="button1">
JQuery
$(document).ready(function(){
$('#destination').change(function(){
$( ".dev" ).remove();
$( "#button1" ).before("<div class='dev' style='float:left;width:280px;'>
<input type='checkbox' value='1' name='ch1[]' class='checkbox'/>Not Working</div>");
});
var $cbs = $('.checkbox');
function calcUsage(){
var total = 0; //$("#more").val();
$cbs.each(function() {
if ($(this).is(':checked'))
{
// total = parseFloat(total) + parseFloat($(this).val());
total = parseFloat($(this).val());
}
});
$("#port").val($("#port").val()-total);
if($("#port").val()<0)
{
alert("Check Your Port Capacity");
}
}
//For checkboxes
$cbs.click(function() {
calcUsage();
});
});
JSFiddle Link
(*this is a sample code but i am populating checkbox on AJAX call for selected destination)
your not binding the new checkboxes that you are adding.
The click event is just binded to the checkboxs that you have when the document is ready. Your new checkboxes are not part of $cbs.
$(document).ready(function(){
$('#destination').change(function(){
$( ".dev" ).remove();
$( "#button1" ).before("<div class='dev' style='float:left;width:280px;'>
<input type='checkbox' value='1' name='ch1[]' class='checkbox'/>Not Working</div>");
});
function calcUsage(){
var total = 0; //$("#more").val();
$('.checkbox').each(function() {
if ($(this).is(':checked'))
{
// total = parseFloat(total) + parseFloat($(this).val());
total = parseFloat($(this).val());
}
});
$("#port").val($("#port").val()-total);
if($("#port").val()<0)
{
alert("Check Your Port Capacity");
}
}
//For checkboxes
$(document).on('click', '.checkbox', function() {
calcUsage();
});
});

Check a DIV for input item values are not empty in jQuery

I've stacked some input text fields, drop downs, radio gruop inside a DIV. Now how do I check if all text fields, radio groups and dropdowns inside this DIV have some value?
I've created a simple mockup in JSFiddle
jQ:
$("#continue_btn").click(function(){
if($('#myForm input:text[value=""]').length > 0){
alert("yes");
} else {
alert("no")
}
}
All you have to do is to wrap your markup in a form element and to each input add attr required
this is pure css.
DEMO ON JSFIDDLE
function highlight(event)
{
event.preventDefault();
alert('Done!!!');
return false;
}
var highlightForm = document.querySelector("form#myForm");
highlightForm.addEventListener('submit',highlight , false);
/**
$("#continue_btn").click(function(){
if($('#myForm input:text[value=""]').length > 0){
alert("yes");
} else {
alert("no")
}
}
*/
<form id="myForm">
<div class="myF">
<div class="input-group">
<span class="input-group-addon"><input type="radio" name="radioGroup" id="radio1" value="option1" required></span>
<input class="form-control" value="Fruits" autofocus required />
</div>
<div class="input-group">
<span class="input-group-addon"><input type="radio" name="radioGroup" id="radio2" value="option2" required></span>
<input class="form-control" value="Vegitables" required/>
</div>
</div>
<div class="input-group">
<span class="input-group-addon quotationFields">City</span><input type="text" class="form-control numericOnly" id="weight_oq" name="weight_oq" required/>
</div>
<div class="input-group onlineQuoteForm">
<span class="input-group-addon">Type </span>
<select class="form-control" id="ptype_oq" required>
<option value="">Please selelct</option>
<option value="Satisfatory">Documents</option>
<option value="val1">OPtion 1</option>
<option value="val2">OPtion 2</option>
</select>
</div>
<input type="submit" value="Continue" id="continue_btn" class="btn btn-primary"/>
</form>
Now you can style it using this
input:required:focus {
}
input:required:hover {
}
/**--------VALID----------*/
input[type="text"]:valid,
input[type="name"]:valid,
input[type="password"]:valid,
input[type="email"]:valid {
}
input[type="text"]:valid:focus,
input[type="name"]:valid:focus,
input[type="password"]:valid:focus,
input[type="email"]:valid:focus {
}
input[type="text"]:valid:hover,
input[type="name"]:valid:hover,
input[type="password"]:valid:hover,
input[type="email"]:valid:hover {
}
/**---------INVALID---------*/
input[type="text"]:invalid,
input[type="name"]:invalid,
input[type="password"]:invalid,
input[type="email"]:invalid {
}
input[type="text"]:invalid:focus,
input[type="name"]:invalid:focus,
input[type="password"]:invalid:focus,
input[type="email"]:invalid:focus {
}
input[type="text"]:invalid:hover,
input[type="name"]:invalid:hover,
input[type="password"]:invalid:hover,
input[type="email"]:invalid:hover {
}
/**---------REQUIRED---------*/
input[type="text"]:required,
input[type="name"]:required,
input[type="password"]:required,
input[type="email"]:required {
}
/**---------OPTIONAL---------*/
input[type="text"]:optional,
input[type="name"]:optional,
input[type="password"]:optional,
input[type="email"]:optional {
}
input[type="text"]:optional:focus,
input[type="name"]:optional:focus,
input[type="password"]:optional:focus,
input[type="email"]:optional:focus {
}
input[type="text"]:optional:hover,
input[type="name"]:optional:hover,
input[type="password"]:optional:hover,
input[type="email"]:optional:hover {
}
The main difficulty here is radio buttons which you need to check separately. Try something like this:
var $form = $('#myForm');
$("#continue_btn").click(function () {
var $radio = $form.find(':radio:checked');
var hasEmpty = $.grep($form.serializeArray(), function(el) {
return !$.trim(el.value);
}).length || $radio.length == 0;
if (hasEmpty) {
alert("yes");
} else {
alert("no")
}
});
Demo: http://jsfiddle.net/tq3jL2d6/9/
Note, that for this demo I improved HTML a little:
wrapped everything with form tag, since you deal with form
added name attributes to all form elements
added placeholder attributes.
You can use this code, here is the link
http://jqueryvalidation.org/files/demo/
And here is the code
view-source:http://jqueryvalidation.org/files/demo/
You can use filter function which can filter every value in form like this
$("#continue_btn").click(function(){
var anyFieldIsEmpty = $("#myForm input,select").filter(function() {
return $.trim(this.value).length === 0;
}).length > 0;
if(anyFieldIsEmpty){
alert("yes");
} else {
alert("no")
}
});
you can select multiple form elements like i have done input,select,textarea etc..
FIDDLE DEMO

array of checkbox value checked and unchecked

I have this function, when I checked one or more checkbox the function load the value of the checked checkbox...but when I unchecked one or more check box the function show an empty array.
this is the function:
$(document).ready(function () {
$('input[type="checkbox"]').change(function () {
var mycheck = new Array();
if ($(this).is(':checked')) {
$("#line-checkbox-1:checked").each(function () {
mycheck.push($(this).val());//aggiungo value del checked
});
alert(mycheck)
} else {
var itemtoRemove = $(this);
mycheck.splice($.inArray(itemtoRemove, mycheck), 1); //rimuovo il value del dechecked
alert(mycheck);
}
});
This is HTML of the checkbox:
<div class="col-lg-3">
<input tabindex="17" id="line-checkbox-1" type="checkbox" name="servizi" value="3">
</div>
Try This Simple Script, this works for you:
HTML
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="3" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
JQUERY
$(document).ready(function ()
{
$('input[type="checkbox"]').change(function ()
{
var arr = $.map($('input:checkbox:checked'), function(e,i) {
return +e.value;
});
alert(arr);
});
});
Its probably because you are using id to reference the checkboxes and since you are creating the array from scratch everytime user changes a checkbox. you should recheck the list everytime a checkbox is changed. That means you dont need that if.( if($(this).is(":checked") )
$('.checkboxes input[type="checkbox"]').change(function () {
var mycheck = new Array();
$(".checkboxes input[type='checkbox']:checked").each(function () {
if ($(this).is(':checked')) {
mycheck.push($(this).attr("id") + ": is " + $(this).val()); //aggiungo value del checked
}
});
alert(mycheck);
});
here is a fiddle if i understand correctly what you are trying to do

Global If Else Statements

http://liveweave.com/EvfTww
I have two radio buttons one says div, and another says remove.
I add in some divs in html and when I select remove I want to be able to remove divs inside of #canvas when clicked.
The function provided below only works when divs are already visible when checked, but when I add new divs in the canvas from the code editor I also want to be able to remove those as well.
Any help is greatly appreciated.
HTML
<table id="main" border="1">
<tr>
<td id="canvas" valign="top"></td>
<td valign="top">
<div id="control_box">
<form id='tools'>
<input name="tool" id="tool-1" checked="checked" type="radio">
<label for="tool-1">DIV</label>
<input name="tool" id="tool-2" type="radio">
<label for="tool-2">Remove</label>
</form><br>
Border Width <select id="divborder">
<option value="1px">1px</option>
<option value="2px">2px</option>
<option value="3px" selected="selected">3px</option>
<option value="5px">5px</option>
<option value="7px">7px</option>
<option value="8px">8px</option>
<option value="9px">9px</option>
<option value="10px">10px</option>
</select><br>
Border Style <select id="divborderstyle">
<option value="dotted">dotted</option>
<option value="dashed">dashed</option>
<option value="solid" selected="selected">solid</option>
<option value="double">double</option>
<option value="groove">groove</option>
<option value="ridge">ridge</option>
<option value="inset">inset</option>
<option value="outset">outset</option>
</select><br>
Border Color
<input id="bcolor" type="text" name="bcolor" value="#f00" /></div><br>
BG Color
<input id="bgcolor" type="text" name="bgcolor" value="#000" onchange="window.set_fill_color(this.value); var col = this.value ; $('#colorSelectorFill').ColorPickerSetColor(col);" /></div>
<input type="button" id="nobg" value="none">
</div><br><br>
<textarea id='code' placeholder="The #canvas acts as page body"></textarea>
</td>
</tr>
</table>
JQuery/JavaScript
$('#tool-2').change(function() {
if ($(this).is(':checked')) {
alert('Remove Tool Chosen! You can now remove divs within the canvas.');
$('#canvas div').on('click', function() {
$(this).remove();
code.val(preview.html());
});
} else {
alert('Houston we have a problem!');
}
});
Try something like;
<input type="radio" name="test" value="div" checked> div
<input type="radio" name="test" value="remove"> remove
$("input[#name='test']").change(function(){
$("#parent_div_id").hide();
});
http://liveweave.com/lXdfqr
Using basically the same function as before, but this time I put it in another function called canvastools, and I removed the else statement as I do not need that for this experiment.
function canvastools(e) {
if ($('#tool-2').is(':checked')) {
$('#canvas div').on('click', function() {
$(this).remove();
code.val(preview.html());
});
}
}
I then call the function by stating that when the document is changed it will call the function.
$(document).change(function(e) {
canvastools(e);
});
I found that using the select element is a bit easier, however it's not exactly isolated. The remove tool's function will still apply even when a another tool/option is selected. I haven't figured out how to fix that problem just yet.
Here's the new fiddle/weave - http://liveweave.com/e5Efnc
function wrappertools(e) {
// Tools
$("select#tools").each(function() {
// DIV Tool
if ($(this).val() === 'div') {
$('#divoptions').show();
$('#spanoptions').hide();
// No Background Option
$('#nobg').click(function() {
$('input[name=bgcolor]').val('none');
});
var bcolor = $('input[name=bcolor]').val(),
bgcolor = $('input[name=bgcolor]').val(),
divborderstyle = $('#divborderstyle').val(),
divborder = $('#divborder').val();
alert('DIV Tool Selected!');
}
// Text Tool
if ($(this).val() === 'text'){
$('#spanoptions').show();
$('#divoptions').hide();
alert('Text Tool Selected!');
// No Background Option
$('#nospanbg').click(function() {
$('input[name=spanbgcolor]').val('none');
});
$('#addspantext').on('click', function() {
var spanbcolor = $('input[name=spanbcolor]').val(),
spanbgcolor = $('input[name=spanbgcolor]').val(),
spanborderstyle = $('#spanborderstyle').val(),
spanborder = $('#spanborder').val(),
spanfont = $('#spanfont').val(),
spancolor = $('#spancolor').val(),
spansize = $('#spansize').val(),
spantext = $('#spantext').val(),
placespan = $('<span style="position: relative; font-family: ' + spanfont + '; font-size: ' + spansize + '; font-color: ' + spancolor + '; border: ' + spanborder + ' ' + spanborderstyle + ' ' + spanbcolor + '; background: '+ spanbgcolor +';">' + spantext + '</span>');
$('.wrapper').append(placespan);
code.val(preview.html());
});
return false;
}
// Remove Tool
if ($(this).val() === 'remove') {
alert('Remove Tool Selected!');
$('#divoptions').hide();
$('#spanoptions').hide();
$('.wrapper div, .wrapper span').on('click', function() {
$(this).remove();
code.val(preview.html());
});
return false;
}
});
}
$(document).ready(function(e) {
wrappertools(e);
});
$(document).change(function(e) {
wrappertools(e);
});

Categories