How to get the checked checkboxes id in to a hidden variable?
I am getting this error.
SyntaxError: unterminated string literal
var test = $('input[name=\'data-grid_c0[]\').val();
data-grid_c0 is the name of the checkbox array.
<input type="checkbox" name="data-grid_c0[]" id="data-grid_c0_1" value="1">
<input type="checkbox" name="data-grid_c0[]" id="data-grid_c0_2" value="1">
<input type="checkbox" name="data-grid_c0[]" id="data-grid_c0_3" value="1">
Below is the jquery code i have written.
$('#deleteall-button').click(function () {
var atLeastOneIsChecked = $('input[name=\"data-grid_c0[]\"]:checked').length > 0;
var test = $('input[name=\'data-grid_c0[]\').val();
alert(test);
if (!atLeastOneIsChecked)
{
alert('Please select atleast one record to delete');
}
else if (window.confirm('Are you sure you want to delete the records?'))
{
document.getElementById('search-form').action = 'index.php?r=device/bulkDelete';
document.getElementById('search-form').submit();
}
});
I want the value of data-grid_c0 to be assigned to selectedDevices hidden field.
<form action="hotelSearch/hotelSearch" method="post"><input id="selectedDevices" type="hidden" value="" name="selectedDevices" /><a id="deleteall-button" class="btn btn-primary">Bulk Delete</a></form>
So with php i will be able to handle it as following and delete,
//check-boxes
if (isset($_POST['selectedDevices'])) { //data-grid_c0
$del_camps = $_POST['selectedDevices']; //data-grid_c0
$model_camp = new Device;
foreach ($del_camps as $_camp_id) {
$model_camp->deleteByPk($_camp_id);
}
}
You're missing a closing ] and a closing '
var test = $('input[name=\'data-grid_c0[]\').val();
Should become
var test = $('input[name=\'data-grid_c0[]\']').val();
As others have pointed out, you don't necessarily have to escape those inner quotes.
var test = $('input[name="data-grid_c0[]"]').val();
You have incorrect selector to target checked check box and also you are not getting the id correctly. Use:
$('input[name="data-grid_c0[]"]:checked').attr('id');
Escaping is not necessarily needed here, you can use meta-characters as a string inside of the selectors.
var atLeastOneIsChecked = $('input[name="data-grid_c0[]"]:checked').length > 0;
var test = $('input[name="data-grid_c0[]"]').val();
And using " inside of a ' wrapped segment would be considered as a string, Don't confuse in that.
Related
Using jquery to get the value of a textbox.
BUT
i need to enter the id of the textbox, then use that value to get the value of the textbox using jquery.
var tt = $("#fieldname").val()
that works
now how do i enter the fieldname at runtime, and get jquery to execute the val command as if it was hard coded?
There are a few ways that you could do this. One way is to listen to one of the keyboard or change events on the textbox you enter the id into, to help determine when the input has changed. So for example
$("#inputText").on("keyup", function(keyupEvent){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
});
Or another way could be to use a click event with similar kind of logic, so for example
$("#clickMe").on("click", function(){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
})
An example for the use case of both can be seen here https://fiddle.jshell.net/xpvt214o/114584/
Here is an example for you to get started with:
<body>
<p>Type "one" or "two" below</p>
<input id="search" />
<input id="one" value="This input is #one" />
<input id="two" value="And this is #two" />
<p id="result">No input specified</p>
</body>
And the corresponding jQuery code:
// Cache jQuery elements for performance and readability
var $search = $("#search");
var $result = $("#result");
$search.on("change", function() {
var search_value = $search.val();
if (search_value.length) {
search_value = "#" + search_value.toLowerCase().trim(); // Sanitise user input
if ($(search_value).length) {
$result.text($(search_value).val());
} else {
$result.text("Input not found");
}
} else {
$result.text("No input specified");
}
});
This will show the value of the specified input, if it exists.
You can see it in action here: https://jsfiddle.net/jeevantakhar/xpvt214o/114558/
I have this:
var category = "3%2C16%2C6%2C10%2C1%2C19";
in witch category id are 3 16 6 10 1 19 and the %2C is the space between category.
What i want is here:
if (document.getElementById("3").checked = false) {
category = "16%2C6%2C10%2C1%2C19";
}
else {
category = "3%2C16%2C6%2C10%2C1%2C19";
}
I want to make this for all the checkbox that i have, but you can't deselect all the checkbox because the servers don't send you back any data.
This is for filtering the results
It would be easier to use an array, then convert it to this string representation, when needed.
var categories = [];
$('#category-form input').change(function () {
var id = $(this).attr('data-id'),
index = categories.indexOf(id);
if (this.checked && index === -1) {
categories.push(id);
} else if (!this.checked && index !== -1) {
categories.splice(index, 1);
}
});
You can see my working code in this fiddle.
(with multiple checkboxes, string representation, and at least one check)
Try
if (document.getElementById("3").checked === false) {
notice the extra double equals to do a typesafe check
or better still
if (!document.getElementById("3").checked) {
However, as you're using jQuery and you appear to be munging a string together from checked states, which is going to be really brittle with hardcoded strings so maybe something like:
var category = "";
$( "input:checked" ).each(function() {
category = $(this).id + "%2C";
};
Only calling that when you need the output e.g. button press.
As you are using jquery, you can listen to the change event for the checkboxes, then build the list each time one is checked or unchecked. To store the values you can either use the value attribute for the checkbox or add data- attributes.
Getting an array of values and joining them will avoid the trailing %2C.
var category = '';
(function($) {
// cache collection of checkboxes
var cboxes = $('input[type=checkbox]');
cboxes.on('change', function() {
// find the ticked boxes only, and make an array of their category values, then join the values by a space
category = $.makeArray(cboxes.filter(':checked').map(function() {
return $(this).data('category');
//return $(this).val(); // if you store them in value="3"
})).join('%2C');
// output for debug purpose
$('#categoryOutput').html("'" + category + "'");
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<input type="checkbox" id="c1" data-category="3" />
<input type="checkbox" id="c2" data-category="16" />
<input type="checkbox" id="c3" data-category="6" />
<input type="checkbox" id="c4" data-category="10" />
<input type="checkbox" id="c5" data-category="1" />
<input type="checkbox" id="c6" data-category="19" />
</form>
<div id="categoryOutput"></div>
Side Note: try to avoid starting element ids with numbers - it is technically invalid and can break things in some scenarios.
I am trying to understand scope as far as inputs and clicks or checks are concerned. I am working on a project and what I am trying to do is. Ask if they work out a lot, they will answer yes or no. then I will ask them 3 question either way. I will ask how much they can bench, how much they can squat, how much they can curl. I have this part set up I will give them feedback based on what they input. What I am trying to do is add a check box to it for them to select if they are male or female. I think I should do it something like this
function one() {
a = 100;
b = 200;
c = 300;
return two();
function two() {
a += a;
b += b;
c += c;
return three();
function three() {
a += 1;
b += 1;
c += 1;
return four();
function four() {
console.log(a, b, c);
}
}
}
}
one()
I guess my question is how would I do this with click and checks and inputs. It seems no matter where I add the check box to what I have, it will not work for some reason. Either there will be a issue with the first question... Do you work out a lot? a the question will not be there. Or I will get a post era. I have a fiddle below. If someone would tell me how to make it work...or even better show me it working, I will be very thankful. I think this would help a lot of people out. I have seen a lot of good answers to this question on here, but no working examples. I think the most helpful thing for some people, is a working example they can see, I know it is for me.
ps in my fiddle i am recycling the same inputs for the questions i'm asking. Whether they work out or not, i would like to do it properly, but not my main issue.
http://jsfiddle.net/vicky1212/G24aQ/10/
I have added some explanation with the code..
$('.myOptions').change(function () {
// Remove the active class
$('.list').removeClass('active');
// Add the active class
// this.value holds the current value that is selected
// No need to use filter
$('.' + this.value).addClass('active');
});
$('#butt').click(function () {
// Better to have Lesser variables ,
var active = $('.list.active'),
$boxOne = active.find('.box1'),
$boxTwo = active.find('.box2'),
$boxThree = active.find('.box3'),
$output = $('#output'),
total = (parseInt($boxOne.val(), 10) + parseInt($boxTwo.val(), 10) + parseInt($boxThree.val(), 10)),
msg = '';
$output.addClass('error');
var dropdownValue = $('.myOptions').val(),
// you need to select the inputs specifically
// you were trying to access it using $('input') that gives the list of all the inputs
// on your page.. So you need to be more specific
$genderRadio = $('input[name=gender]');
// If dropdown is empty show some message
if (dropdownValue === '') {
msg = 'Please select an option....';
} else if (isNaN(total)) {
msg = 'Input three numbers, please...';
} // If gender is not selected show a specific message
else if ($genderRadio.filter(':checked').length === 0) {
msg = 'Please select your gender....';
} else {
// If it comes to this statemenet it means there is no error
// remove the error class
$output.removeClass('error');
if (total < 14) {
msg = "That's bad, should be higher...";
} else if (total > 15) {
msg = "That's bad, should be lower...";
} else {
msg = "You got it... Nice work.";
}
var genderPrefix = $genderRadio.filter(':checked').val() === 'Male' ? 'Sir..' : 'Miss..';
msg = genderPrefix + msg;
}
$output.text(msg);
});
Check Fiddle
I will give an little introduction to javascript pattern with my example. you can read about them in http://addyosmani.com/resources/essentialjsdesignpatterns/book/ is not a easy reading but when you are ready you will understand pretty much about how to organize you javascript code with that book.
meanwhile I can advise you to read about how to code forms with good practices at http://net.tutsplus.com/tutorials/html-css-techniques/20-html-forms-best-practices-for-beginners/
Ok beside that here are the working example about how to work with click and forms http://jsfiddle.net/ncubica/BQaYz/
HTML
<label><input type="Radio" name="gender" id="male" value="male" /> male</label>
<label><input type="Radio" name="gender" id="female" value="female" />female</label>
<input type="text" id="name" placeholder="name" />
<input type="text" id="lastname" placeholder="lastname" />
<input type="button" id="submit" value="store" />
javascript
var survey = (function(_module){
var modulename = _module;
var user = {};
/*private methods*/
function init(){
observers();
}
function observers(){
$(document).on("click","#submit", survey.store)
}
/*public methods*/
$r = {}
$r.store = function(){
user.name = $("#name").val();
user.lastname = $("#lastname").val();
user.gender = $("input:radio[name=gender]:checked").val();
survey.toString();
}
$r.toString = function(){
var genderStr = (user.gender == "male") ? "Man" : "Girl";
alert(user.name + " " + user.lastname + " is " + genderStr);
}
$r.init = function(){
init();
}
return $r;
})("survey")
survey.init();
Ok, I know at first look a little "big" code but is really simple, in javascript a variable can take any kind of form from a function to a normal string.
here we are working with anonymous functions to create a module will help us to work more clear and structure, this variable will have 2 kind of methods and variable, public and privates.
for make a method public we have to return the methods in an object after we finish to run the code this is why exist the $r variable which is an object who have function by properties, and at the end of the code you return it doing return $r with this pattern now you can easily can navigate throw methods and catch events like click, change, etc....
you only should have to add this event to the method observers create a private or public function which will be activate after the event an you are done.
Read the code and if you have any further question you can ask me anything. I try to solve you problem and structure you code.
best good luck
[Here is below answer as a jsFiddle]
This answer is intended as a starter. I tried to write it at a beginner level, so that you can customize it for yourself. Hopefully, this simple example can give you a starting place. I used the example of a training gym asking some basic questions of their users.
My approach was to create an empty DIV, called #ques, where all Questions and output will be displayed, and a hidden <form> containing hidden fields that will store the responses.
I created a counter, cnt, which is incremented after each question.
There is a function called ask_next_ques() that takes the parameter cnt. Depending on where we are in the survey, it asks the next question (eg. when cnt==3 it asks the third question).
Unfortunately, javascript insists that all strings be on one line. Therefore, I built the html like this:
var qq = '
<ul style="list-style:none">
<li>
What can you curl?<br />
<input type="text" id="curl"> Kg
</li>
<li>
What can you bench?<br />
<input type="text" id="bench"> Kg
</li>
<li>
What can you lift?<br />
<input type="text" id="lift"> Kg
<input type="button" id="cbl_btn" value="Go">
</li>
</ul>
';
and then re-arranged it onto one line, like this:
var qq = '<ul style="list-style:none"><li>What can you curl?<br /><input type="text" id="curl"> Kg</li><li>What can you bench?<br /><input type="text" id="bench"> Kg</li><li>What can you lift?<br /><input type="text" id="lift"> Kg<input type="button" id="cbl_btn" value="Go"></li></ul>';
Much more difficult to read that way, but that's how javascript wants things.
As each question is answered, the responses are read by javascript/jQuery and then saved into hidden fields inside the <form> structure.
When all questions have been asked, you can just POST the form to another (PHP?) file for processing (storage in a MySQL database?), or email the answers to yourself, or re-display them to the user, or... I chose to display the answers in a lightbox.
Here is all the code. Just copy/paste it into a single HTML or PHP file, and run.
SURVEY.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" /><!--Lightbox-->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script><!--Lightbox-->
<style>
</style>
<script type="text/javascript">
//Declare vars outside document.ready() so they can be accessed globally
var ctr = 1;
var mf = '';
var pl = '';
$(document).ready(function() {
ask_next_ques(ctr);
/* ------------------------------------------------------------ */
$("input:radio[name=gender]").click(function() {
//Note: var mf must be initialized above (outside document.ready() ) so can be used in below fn ask_next_ques()
mf = $('input:radio[name=gender]:checked').val();
$('#hgender').val(mf);
ctr++;
ask_next_ques(ctr);
});
/* ------------------------------------------------------------ */
$(document).on('click', "#cbl_btn", function() {
var cc = $("#curl").val();
var bb = $("#bench").val();
var ll = $("#lift").val();
//alert('Value of cc: ' +cc+ ' Value of bb: ' +bb+ ' Value of ll: ' + ll);
//Check if any one of these fields left empty
if (cc.length<1 || bb.length<1 || ll.length<1) {
alert("Please complete all fields");
}else{
$('#hcurl').val(cc);
$('#hbench').val(bb);
$('#hlift').val(ll);
ctr++;
ask_next_ques(ctr);
}
});
/* ------------------------------------------------------------ */
$(document).on('click', "input:radio[name=plan]", function() {
//Note: var pl must be initialized above so can be used in below fn ask_next_ques()
pl = $('input:radio[name=plan]:checked').val();
$('#hplan').val(pl);
ctr++;
ask_next_ques(ctr);
});
/* ------------------------------------------------------------ */
}); //END $(document).ready()
function ask_next_ques(ctr) {
if (ctr==1) {
var qq = 'Male: <input value="Male" type="radio" name="gender"><br />Female: <input value="Female" type="radio" name="gender">';
$('#ques').html(qq);
}else if (ctr==2){
var qq = '<ul style="list-style:none"><li>What can you curl?<br /><input type="text" id="curl"> Kg</li><li>What can you bench?<br /><input type="text" id="bench"> Kg</li><li>What can you lift?<br /><input type="text" id="lift"> Kg<input type="button" id="cbl_btn" value="Go"></li></ul>';
$('#ques').html(qq);
}else if (ctr==3){
var qq = 'Are you an:<br />Owner: <input value="Owner" type="radio" name="plan"><br />Member: <input value="Member" type="radio" name="plan">';
$('#ques').html(qq);
}else if (ctr==4){
//All questions have been asked; All responses saved into hidden fields
//Can now read all hidden fields and do an AJAX POST into the database, or
//Or can simply POST the form to another page for processing.
alert("All questions have been asked");
var hg = $('#hgender').val();
var hc = $('#hcurl').val();
var hb = $('#hbench').val();
var hl = $('#hlift').val();
var hp = $('#hplan').val();
qq = 'The values saved into all hidden fields are:<br />Gender: ['+hg+ ']<br />Curl: [' +hc+ ']<br />Bench: [' +hb+ ']<br />Lift: [' +hl+ ']<br />Plan: [' +hp+ ']<br />You can now send these values to a<br />database, or email them to yourself.';
$('#ques').html(qq);
//We could just leave it here, but to be interesting we'll display the results in a lightbox
//To remove all lightbox stuff, just delete the next 8 lines and delete the two lightbox references in the header (for jquery-ui)
$('#ques').dialog({
autoOpen:true,
width: 450,
title: "Hidden Field Valuess:",
close: function() {
alert('Thank you for taking our survey');
}
});
}
}
</script>
</head>
<body>
<div id="ques"></div>
<div id="hidden_form">
<form method="POST">
<input type="hidden" id="hgender" name="gender">
<input type="hidden" id="hcurl" name="curl">
<input type="hidden" id="hbench" name="bench">
<input type="hidden" id="hlift" name="lift">
<input type="hidden" id="hplan" name="owner">
</form>
</div>
</body>
</html>
I have an extense form with around 25 inputs (text, radio and checkboxes). I want that when I click the button that opens the jQuery dialog, loads the form and set all fields except 5 of them disabled. Seems so easy, but I want that into a "generic" function. I mean, that I have this method:
function disableInputs(jQueryElement, exceptions, booleanClean) {
//Some stuff
}
I want to get all the inputs from the jQueryElement, but ignoring all the elements with the ids that have exceptions. Exceptions is an Object like this one:
var exceptions = {
0: 'clientId',
1: 'clientName',
2: 'clientFirstSurname',
3: 'clientSecondSurname',
4: 'clientAlias'
}
This is my full code and what I've tested, but this is the only way to make it work and, if I have recieved the third parameter (booleanClean), It will set value='' to all inputs, instead to the elements that weren't excluded from being disabled. That boolean works to check if you want to clean inputs when this function is called:
function disableInputs(jQueryElement, exceptions, booleanClean) {
var inputs = jQueryElement.find('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute('disabled', true);
for (var attr in exceptions) {
if (inputs[i].getAttribute('id') === exceptions[attr]) {
inputs[i].removeAttribute('disabled');
} else {
if (booleanClean === true) {
inputs[i].value = null;
}
}
}
}
}
I know why is not working the clean "option". What I want is where I have to put that to do it properly or if I can set a condition when I get the inputs to get only the inputs that are not excluded (preferible second option for optimization and not set an attribute to each input and remove them if are excluded. Seems much easier to work).
I'd suggest changing the exceptions object to be a conventional array:
var exceptions = ['clientId',
'clientName',
'clientFirstSurname',
'clientSecondSurname',
'clientAlias'];
...because then you can simplify your function a lot:
function disableInputs(jQueryElement, exceptions, booleanClean) {
var inputs = jQueryElement.find('input');
if (exceptions.length > 0) {
exceptions = "#" + exceptions.join(",#");
inputs = inputs.not(exceptions);
}
inputs.prop("disabled",true);
if (booleanClean)
inputs.val("");
}
I'm a bit confused about whether you want to clean all inputs or just the ones not on the exceptions list. My code above just cleans those not on the list. To clean them all move that if(booleanClean) inputs.val(""); to before the other if statement.
Try
function disableInputs(jQueryElement, exceptions, booleanClean) {
var not = jQuery.map(exceptions, function(item, index){
return '#' + item;
}).join(',')
var inputs = jQueryElement.find(':input').not(not).prop('disabled', true);
if(booleanClean){
inputs.val('')
}
}
Are you able to give a class name to the items that are exceptions? That's what I would do.
<input class="exception" />
$( "input:not(.exception)" ).prop("disabled", true);
Try this one:
HTML
<form>
<input type="text" name="input1" value="val1" />
<input type="text" name="input2" value="val2" />
<input type="text" name="input3" value="val3" />
</form>
JS
function disableInputs(jQueryElement, exceptions, booleanClean) {
jQueryElement.find('input').not( exceptions.join(', ') ).each(function(){
if( booleanClean ){
$(this).val('');
}
$(this).prop('disabled', true);
});
}
var exceptions = ['input[name=input1]', 'input[name=input3]'];
disableInputs( $('form'), exceptions, true );
Here is working sample: http://jsfiddle.net/4Dwwk/
hi guys i have a html form where i have a textfield which is having capabilities to enter two digits the first digit is autopopulated to be 0 and i donot want users to change that hows that possible using javascript or jQuery or anything else.
Here is another way.
the onKeyUp might not be how you want it to work but at least you have some ideas
<script>
window.onload=function() {
document.getElementById('part2').focus();
}
</script>
<form onSubmit="this.realvalue.value='0'+document.getElementById('part2').value">
<input type="text" name="realvalue" value="">This can be hidden<br />
<input type="text" style="border-right:0; width:12px" value="0" readonly="readonly" size="1"><input type="text" id="part2" style="border-left:0; width:13px" size="1" maxsize="1"
onKeyUp="this.value=(this.value.length>1)?this.value.substring(-1):this.value">
<input type="submit">
You can use the event "keyup" triggered when the user enters text in the field:
$('#my-input').keyup(function() {
var theInputValue = $(this).val();
// Do whatever you want with the value (like check its length,
// append 0 at the beginning, tell the user not to change first
// character
//
// Set the real value
$(this).val(newValue);
});
You may be better off with a '0' as text in front of a textbox that can only accept a single digit and then prepend the '0' programmatically?
I wrote and tested this code, and works exactly as you expect:
$(function (){
$('#input_id').bind('input',function (){
var val = $(this).val();
var r = val.match(/^[0][0-9]$/g);
if (r !== null){
val = r[0];
if (val.length === 1){
val = '0' + val;
}
}else{
val = '0';
}
$(this).val(val);
});
});
And works for copy/paste too =]