if statement using jquery selectors and checkboxes - javascript

I have a form with two text input fields and a series of checkboxes.
There is a variable fields which stores some arrays with data pertaining to the selected fields. I have hardcoded the values into the script with no problem but I cannot seem to find out how to properly compose an if statement to check the status of the checkboxes and only use those values, rather than hardcoding the selected fields.
var start, end, fields;
$(function() {
$("#form1").submit(function(event) {
var endD = $("#endDate").val();
end = endD;
var startD = $("#startDate").val();
start = startD;
//fields = ['PM1','PM2.5','PM10'];
//if $("#PM1").is("checked"))){
//fields = ["PM1"];
//}
if ($("PM1").attr("checked")) {
fields = ["PM1"];
}
event.preventDefault();
build_graph();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
Start Datetime:<br>
<input type="text" name="startDate" id="startDate" class="Date" placeholder="YYYYMMDD-HHMM"><br> End Datetime <br>
<input type="text" name="startDate" id="endDate" class="Date" placeholder="YYYYMMDD-HHMM"><br> Parameter
<br>
<input type="checkbox" class="parameter" id="PM1">PM1<br>
<input type="checkbox" class="parameter" id="PM2.5" checked>PM2.5<br>
<input type="checkbox" class="parameter" id="PM10">PM10<br>
<input type="checkbox" class="parameter" id="Temp">Temperature<br>
<input type="checkbox" class="parameter" id="Humidity">Humidity<br>
<input type="checkbox" class="parameter" id="Pressure">Pressure<br>
<input type="checkbox" class="parameter" id="WindSpeed">Wind Speed<br>
<input type="checkbox" class="parameter" id="Direction">Direction<br>
<input type="checkbox" class="parameter" id="RainVolume">Rain Volume<br>
<input type="submit">
</form>

You can select only the checked checkbox, using a JQuery selector :
$('.myCheckboxs:checked')
this will give you only the checked one.

with jQuery you can properly check if a checkbox is checked like:
if($('#mycheckbox').prop("checked")){
// it´s checked
}
my tip, use this function that serializes your form into an object
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
you can then serialize your form like this:
fields = $("#form1").serializeObject()
all input values and checkboxes that are checked will occur as property

Related

How to concatenate form array inputs before submission?

Example code:
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
On form submission the URL should look like:
http://some-website.tld/action?anythingOne=one,three&otherThingTwo=Fifty
What I am observing now is,
http://some-website.tld/action?anythingOne=one&anythingOne=three&otherThingTwo=Fifty
The serialize() or serializeArray() is not working in this case. Any ideas?
You could grab the result of .serializeArray and transform it into the desired format:
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
var data = $(this).serializeArray();
var dataByKey = data
.reduce((result, entry) => {
var name = entry.name.replace(/\[\]$/, '');
(result[name] || (result[name] = [])).push(entry.value);
return result;
}, {});
Object.keys(dataByKey)
.forEach((key, _) => dataByKey[key] = dataByKey[key].join(','));
console.log(dataByKey);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<fieldset>
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
</fieldset>
<fieldset>
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
</fieldset>
<input type="submit" />
</form>
If you want, you can also use pure javascript without jQuery to get all the checked checkboxes' value, http://jsfiddle.net/jx76dpkh/1/
<form id="myForm" method="get">
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
<input type="submit" />
</form>
JS:
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', (e) => {
e.preventDefault();
let checkboxes = Array.from(myForm.querySelectorAll('input[type="checkbox"]:checked');// build the array like element list to an array
let anythingOne = checkboxes.filter( box => box.name === 'anythingOne[]').map(item => item.value);
let otherThingTwo = checkboxes.filter( box => box.name === 'otherThingTwo[]').map(item => item.value);
});
In case, you are allowed to change html, here is a solution using hidden fields.
function updateChecks() {
$.each(['anythingOne', 'otherThingTwo'], function(i, field) {
var values = $('input[type=checkbox][data-for=' + field + ']:checked').map(function() {
return this.value;
}).get().join(',');
$('input[type=hidden][name=' + field + ']').val(values);
});
}
$(function() {
$('form').on('submit', function(e) {
updateChecks();
});
updateChecks();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="hidden" name="anythingOne" value='' />
<input type="hidden" name="otherThingTwo" value='' />
<input type="checkbox" data-for="anythingOne" value='one' checked='' />
<input type="checkbox" data-for="anythingOne" value='two' />
<input type="checkbox" data-for="anythingOne" value='three' checked='' />
<input type="checkbox" data-for="otherThingTwo" value='Forty' />
<input type="checkbox" data-for="otherThingTwo" value='Fifty' checked='' />
</form>
You could get query string parameters using by serializeArray() method. Then use reduce() to group parameter values by name, and map() to get array of key-value pairs. Then it is possible to concatenate the pairs separated by & using join() method. For example the following snippet creates a target URL using actual value of the form action (current URL by default) and values of checked checkboxes:
$('form').submit(function() {
var queryString = $(this).serializeArray()
.reduce(function(transformed, current) {
var existing = transformed.find(function(param) {
return param.name === current.name;
});
if (existing)
existing.value += (',' + current.value);
else
transformed.push(current);
return transformed;
}, [])
.map(function(param) {
return param.name + '=' + param.value;
})
.join('&');
var action = $(this).prop('action');
var delimiter = (~action.indexOf('?')) ? '&' : '?';
$(this).prop('action', action + delimiter + queryString);
// Only for display result. Remove on real page.
var url = $(this).prop('action');
console.log(url);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="GET">
<input type="checkbox" name="anythingOne" value='one'>
<input type="checkbox" name="anythingOne" value='two'>
<input type="checkbox" name="anythingOne" value='three'>
<input type="checkbox" name="otherThingTwo" value='Forty'>
<input type="checkbox" name="otherThingTwo" value='Fifty'>
<button type="submit">Show target URL</button>
</form>
The latest 3 lines are used only to prevent the form sending and display resulted URL.
Also it is possible to solve the question using only serialize() mathod and regular expressions, but it requires lookbehind assertion support in browsers.
You can collect all the checked boxer and join the different parts of the strings.This may not be the most neat or efficient solution, but it works. I used a button to trigger the concatenation. See my comments within the code.
$(document).ready(function(){
$("button").click(function(){
/* concatenate anythingOne form*/
//collect anythingOne input
var joined_serialized = []
var anythingOne = [];
$.each($("input[name='anythingOne[]']:checked"), function(){
anythingOne.push($(this).val());
});
//join otherThingTwo input
var anythingOne_serialized = "";
if(anythingOne.length > 0){ //only collect if checked
anythingOne_serialized = "anythingOne=" + anythingOne.join(",");
joined_serialized.push(anythingOne_serialized)
}
/* concatenate otherThingTwo form*/
//collect otherThingTwo input
var otherThingTwo = []
$.each($("input[name='otherThingTwo[]']:checked"), function(){
otherThingTwo.push($(this).val());
});
//join otherThingTwo input
var otherThingTwo_serialized = "";
if(otherThingTwo.length > 0){ //only collect if checked
otherThingTwo_serialized = "otherThingTwo=" + otherThingTwo.join(",");
joined_serialized.push(otherThingTwo_serialized)
}
/*join different form names*/
var joined_serialized = joined_serialized.join("&")
if(joined_serialized.length == 1){ //remove last & if only one form is checked
joined_serialized = joined_serialized.slice(0, -1)
}
/*concatenated forms with website*/
var result = "http://some-website.tld/action?"+joined_serialized
console.log(result) //E.g. when Two, Three and Forty are checked: http://some-website.tld/action?anythingOne=two,three&otherThingTwo=Forty
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
<button>submit<button/>

Javascript: How to check if each input value is duplicated to another input value

So i have a dynamic input field came from append with different class name and names, i want to check each of input field value already exist or duplicate.
This would look like
The first criteria_name is default and the others are appendend.
<input type="text" name="criteria_name" class="criteria_name">
<input type="text" name="criteria_name2" class="criteria_name2">
<input type="text" name="criteria_name3" class="criteria_name3">
<input type="text" name="criteria_name4" class="criteria_name4">
<input type="text" name="criteria_name5" class="criteria_name5">
I am trying to check each one of those if there is no duplicated else proceed.
var critname_arr = [];
var input_check;
var crit_name_of_first = $('input.criteriaNames').val();
var acappended = append_crit_header+1;
var count_to = 0;
for(var ab = 2; ab<=acappended; ab++){
var crit_arr;
if(crit_name_of_first == $('input.criteria_each_name'+ab+'').val()){
alert("Criteria cannot be duplicate");
return false;
}else{
input_check = $('input.criteria_each_name'+ab);
input_check.each(function(){
crit_arr = $.trim($(this).val());
});
critname_arr.push(crit_arr);
}
if($('input.criteria_each_name'+ab+'').val() == critname_arr[count_to]){
alert('criteria cannot be duplicate');
return false;
}
count_to++;
}
console.log(critname_arr);
Here is just an example of how you can do it. In the fiddle change one of the values to one that is already in another field (make a duplicate value) to see it do something. If there are no duplicates, it will not do anything. Click the "Button" text to run the duplicate check:
jsFiddle: https://jsfiddle.net/o52gjj0u/
<script>
$(document).ready(function(){
$('.ter').click(function(e) {
var stored = [];
var inputs = $('.criteria_name');
$.each(inputs,function(k,v){
var getVal = $(v).val();
if(stored.indexOf(getVal) != -1)
$(v).fadeOut();
else
stored.push($(v).val());
});
});
});
</script>
<!-- Just use an array name for the input name and same class name as well -->
<div class="ter">Button</div>
<input type="text" name="criteria_name[]" class="criteria_name" value="1" />
<input type="text" name="criteria_name[]" class="criteria_name" value="2" />
<input type="text" name="criteria_name[]" class="criteria_name" value="3" />
<input type="text" name="criteria_name[]" class="criteria_name" value="4" />
<input type="text" name="criteria_name[]" class="criteria_name" value="5" />

Pass jQuery array value on submit as hidden input

On button press the following code will display a message with values collected from all checkboxes. But I want to pass these values (returned by function) as hidden input on submit.
<form action="script.php" method="post">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="button" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('btntest').onclick = function(){
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
//-->
</script>
I've seen guys like you trying to code my router interface, so I'll help out.
give your form an id cause you'll need it later
<form action="script.php" method="post" id="the_form">
add the hidden input in the form
<input type="hidden" name="values" id="values" value="" />
the button in the form matures to a real submit (amazing)
<input type="submit" ...
your "getSelectedChbox()" function is amazing; don't change anything there, just wanted to give you congratulations for it, it's a great function
now, where it says document.getElementById('btntest').onclick - get rid of all that and add this code instead; this code will do the rest.
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
Or simply copy-paste this whole thing in a file called script.php:
<?php echo var_dump(isset($_POST['values']) ? $_POST['values'] : 'Submit first.'); ?>
<form action="script.php" method="post" id="the_form">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="hidden" name="values" id="values" value="" />
<input type="submit" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true)
selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
//-->
</script>
Have fun.

jquery send 2 values from radio button

I been working on this for more of 8 hours trying different scripts Like: if/else, creating 2 names and values, creating "hidden" input with the name and values, create JavaScript but the jQuery brake, here is what I have thanks to #Mood http://jsfiddle.net/LZ5Uz/4/ : Now my first variable I need to post is "amount" (I have that one) but I need to send "recurring" from the same radio checked. Example:
<input name="amount" id="result" type="hidden" />//Here I will send the variable "amount"
Now for the variable "recurring" I was trying:
<input id="q" type="radio" name="presets,recurring" class="q" value="12,Quarterly" />Quarterly
<labels id="choice_q" class="q"></label> //JQuery break
Try:
$('input:radio[name="presets"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'monthly') {
}
});
I am a noob on this... The variable and value I need to send is: (variable-->) name="recurring" (value -->) first radio is checked = "monthly" second radio checked = "quarterly" third radio checked = "year"
Demo jsFiddle
Description
To solve the above problem I used knockoutjs the reason is this is meant for this type of UI (UX). jQuery isn't meant for this type of design.
HTML
<div>
<input id="amount" type="number" data-bind="value: Amount" />
</div>
<div>
<input id="m" type="radio" name="presets" value="0" data-bind="checked: RecurringOption, value: Option1" />
<label for="m" id="choice_m" data-bind="text: Option1"></label>
<input id="q" type="radio" name="presets" value="1" data-bind="checked: RecurringOption, value: Option2" />
<label for="q" id="choice_q" data-bind="text: Option2"></label>
<input id="y" type="radio" name="presets" value="2" data-bind="checked: RecurringOption, value: Option3" />
<label for="y" id="choice_y" data-bind="text: Option3"></label>
</div>
<input id="result" type="text" readonly="readonly" />
<input id="recurringOption" type="hidden" data-bind="value: RecurringOption" />
JS
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
var self = this;
this.Amount = ko.observable(50);
this.RecurringOption = ko.observable();
this.Option1 = ko.computed(function () {
if (self.Amount() != null) return (parseFloat(self.Amount(), 10) / parseFloat(36, 10)).toFixed(2);
return 0;
}, self);
this.Option2 = ko.computed(function () {
if (self.Amount() != null) return (parseFloat(self.Amount(), 10) / parseFloat(12, 10)).toFixed(2);
return 0;
}, self);
this.Option3 = ko.computed(function () {
if (self.Amount() != null) return (parseFloat(self.Amount(), 10) / parseFloat(3, 10)).toFixed(2);
return 0;
}, self);
}
$(function () {
// Activates knockout.js
ko.applyBindings(new AppViewModel());
$("input[name='presets']").change(function () {
var id = $("input:checked").attr("id");
$("#result").val($('#' +id).val());
});
});

Checkbox and text field, if one is selected or has value require other(s)

I have two checkboxes in a group and one text input. If one (or both) of the checkboxes are selected I need to have the text input be required, as well as if the text input has text I need at least one of the checkboxes to be required. Another problem I'm having it that it's using a custom templating engine (PHP backend) and is a pain to configure and get the attributes correct, another issue is it's all referenced by the name attribute and this is why I'm using a HTML5 data-group for the checkbox options which I think it working.
Any help in getting this to work, combining functions (if this makes it easier/simpler).
BTW it's running 1.3.2 jQuery
Example: (not working)
http://jsfiddle.net/NYn8e/1/
Any suggestions?
JS:
function checkboxSelectedRequiredAdditionalFields(elem) {
var passedElement = $('input:checkbox[name=' + elem + ']');
passedElement.click(function() {
$('input[name=number]').attr('required', true).append('<span class="required">*</span>');
alert('text is required now?');
});
}
function numberEnteredRequiredAdditionalFields(elem) {
var passedElement = $('input[name=' + elem + ']');
if (passedElement.val().length > 0) {
var boxes = $('input[data-group=cbOptions]').click(function() {
boxes.not(this).attr('required', false);
alert('checkbox is selected so other checkbox is not required');
});
$('input[data-group=cbOptions]').each(function() {
$(this).attr('required', true).next().append('<span class="required">*</span>');
alert('checkbox is required now?');
});
}
}
HTML
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox1');" data-group="cbOptions">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox2');" data-group="cbOptions">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" onclick="numberEnteredRequiredAdditionalFields('number');">
</b>
</form>
You should separate the JavaScript from the HTML. Fiddle: http://jsfiddle.net/NYn8e/6/. If possible, remove <b> from the HTML source, and extend the style sheet with the right CSS property: font-weight: bold;.
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" data-required="checkbox">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" data-required="checkbox">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" data-required="number">
</b>
</form>
JavaScript:
function required(){
//Any checked checkbox? checked == 0 = no, otherwise: yes
var checked = $('input[data-required=checkbox]:checked').length;
var $checkboxes = $('input[data-required=checkbox]');
var $num = $('input[name=number]');
var length = $num.val().length;
//Remove previously added span, if existent.
$num.next('span.required').remove();
$checkboxes.next('span.required').remove();
if(!length && checked){
$num.after('<span class="required">*</span>');
alert("Number required!");
} else if(length && !checked){
$checkboxes.after('<span class="required">*</span>');
alert("Check at least one checkbox.");
}
}
$(document).ready(function(){
$("[data-required]").change(required);
});
=) Would this one help you?
<form id='myForm'>
<input type='checkbox' name='checkbox1' value='t' id='checkbox1' onchange='alertUser()' />
<input type='checkbox' name='checkbox2' value='t' id='checkbox2' onchange='alertUser()' />
<input type='text' name='number' id='number' onchange='alertUser()'/>
</form>
<script type='text/javascrip>
function alertUser() {
var checked1 = $('#checkbox1').attr('checked');
var checked2 = $('#checkbox2').attr('checked');
var number = $('#number').val();
if ((checked1 == true || checked2 == true) && number == '') {
alert('Number is required!');
} else if (number != '' && (checked1 != true && checked2 != true)) {
alert('One of the checkbox need to be checked!');
}
});
</script>
This should hopefully give you an idea on how to accomplish the task. http://jsfiddle.net/NYn8e/8/
var $textbox = $('input[name=number]').hide();
$('input[type=checkbox]').change(function() {
var $this = $(this); //store jquery object
//get the other checkbox
var $other= ($this.attr('name') === 'checkbox1') ? $('input[name=checkbox2]') : $('input[name=checkbox1]');
if (!$other.is(':checked') && !$this.is(':checked')) {
$textbox.val('').hide();
} else{
$textbox.show();
}
});

Categories

Resources