javascript modify variable - javascript

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.

Related

Check number of checkboxes depending on input

I have this following checkbox on my page
<div class="col-sm-6">
<label>Product Show</label>
<input type="checkbox" name="edprodShow" value="1" >Shape<br>
<input type="checkbox" name="edprodShow" value="2" >Color<br>
<input type="checkbox" name="edprodShow" value="3" >Design<br>
</div>
I would get values like 1 or 2 or 3(Externally, like in a JSON and i would extract that data). I want to set first check box if 1 and 1st and 2nd if two check box and all three if I get 3.(i.e) Get only shape for 1 and color + shape for 2 and color+shape+design for 3
I have tried many sources and ways but not finding the appropriate output how can I do it ?
Edit :
Code I tried to do
if(split_data[7].toString() === "1"){
$('#edprodShow').prop('checked', true);
}else if(split_data[7].toString() === "2"){
}else if(split_data[7].toString() === "3"){
$('#edprodShow').prop('checked', true);
}
where split_data[7] gives me 1,2 or 3
Try this.
Sample Json from server
var json = { edprodShow: [1,2,4]};
Code
var checker = function(data){
$("[name='edprodShow']").attr('checked', false);
$.each(data.edprodShow, function(i, value){
$("[name='edprodShow'][value='"+ value +"']").attr('checked', true);
}
}
Call the function
checker(json);
I got the solution dear ☺
you can do this by javascript :
$(document).ready(function(){
var $checkboxes = $('#devel-generate-content-form td input[type="checkbox"]');
$checkboxes.change(function(){
var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
// $('#count-checked-checkboxes').text(countCheckedCheckboxes);
$('#edit-count-checked-checkboxes').val(countCheckedCheckboxes);
})
Here you can see Demo

Get html checkbox list checked values to a hidden field

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.

updating values of an array through <input> tags

I have the following three tag:
<input class="forLoopIndex" id="typicalElement" type="text" name="k" size="1" placeholder="10">
<input class="forLoopIndex" type="text" name="n" size="1" placeholder="n">
<input class="forLoopIndex" type="text" name="i" size="1" placeholder="i">
Now I have an event listener that checks when a value comes in, and then stores it in an array. I want the array to be kept at 3 values only. Cause I need to use the third and the second for something, but I need to see when they change. Here is the JS for that:
forloops.keyup(function () {
if (forLoopIndex.length < 2 && forLoopIndex >= 0) {
forloops.each(function () {
forLoopIndex.push($(this).val());
appendingToSigmaLimit();
console.log(sigmaLimit.val());
console.log(forLoopIndex);
});
} else if (forLoopIndex.length > 2) {
forLoopIndex = [];
}
});
Now, the problem is that, the values will only update until I have changed the values of the three inputs again. I have a feeling that the way of the logic is in my JS is making it do that. I just need to update the values every time that I change a value on one of my inputs. Any ideas?
Thanks,
M
Not sure what you expected, something like this will update each input separatly
var forloops= $('.forLoopIndex');
var forLoopIndex = [];
forloops.keyup(function () {
forloops.each(function (i, e) {
forLoopIndex[i] = $(this).val();
console.log(i);
console.log(forLoopIndex);
});
});
FIDDLE
Edit without loop:
var forloops= $('.forLoopIndex');
var forLoopIndex = [];
forloops.keyup(function () {
forLoopIndex[$(this).index('.forLoopIndex')] = $(this).val();
console.log(forLoopIndex);
});
FIDDLE

javascript multidimensional array creation and insertion

Hello I want to create an array in javascript
var sortValues = array(
2 => array(3,4,5),
3 => array(5,6,7),
12 => array (7,4,5)
);
Now I am looping through all textboxes of my form. Every textbox has id like 2_3 means 2 will be the main index of the array.
My html markup looks like
<input type="text" value="3" id="2_5" name="2_5">
<input type="text" value="4" id="2_5" name="2_6">
<input type="text" value="5" id="2_5" name="2_7">
<input type="text" value="5" id="3_1" name="3_1">
<input type="text" value="6" id="3_2" name="3_2">
..................................
Now I want to check if 2 exists in array sortValues, I will take the value of the text box and and will check if this value exists in the array against 2 then I will put an alert that value already exists, if value doesn't exists push the value in sub array. Means I need to put 3 against 2 I will check if 3 exists against 2, if yes put alert else push in array.
If 2 (main index) doens't exist create a new index in array and so on. I have tried so far
var sortvalues = new Array();
$(":text").each(function () {
if($(this).val() != '') {
id = $(this).attr('id');
ids = id.split("_");
parent = ids[0];
child = ids[1];
if(typeof sortvalues[parent] !== 'undefined') {
if(typeof sortvalues[parent][$(this).val()] !== 'undefined') {
alert("Value already exists");
} else {
sortvalues[parent][] = $(this).val();
}
} else {
sortvalues.push(parent);
}
}
});
console.log(sortValues);
Which gives ["2", "2", "2"] which is wrong. Can Any body guide me how can I achieve above mentioned array in above mentioned criteria ??/
Do you mean to create an array in another array?
For example :
var sortValues = new Array();
sortValues[2] = Array(3,4,5);
Please clarify your question. And the following:
sortvalues[parent][] = $(this).val() --> you can't leave empty for the second array.

Auto populate the textbox value with values checked in checkboxes but retain the values that are manually entered

I used the jquery below to auto populate a textbox based on values of checked or unchecked check boxes
function updateTextArea() {
var allVals = [];
$('#all :checked').each(function () {
allVals.push($(this).val());
});
document.getElementById('txtbox').value = allVals;
}
$(function () {
$('#all input').click(updateTextArea);
updateTextArea();
});
and my html code is
<div id="all">
<input id="txtbox" type="text" Height="100px" Width="770px" />
<input id="Checkbox2" type="checkbox" value="abc1#abc.com" />
<input id="Checkbox3" type="checkbox" value="abc2#abc.com" />
<input id="Checkbox4" type="checkbox" value="abc3#abc.com" />
<input id="Checkbox5" type="checkbox" value="abc4#abc.com" />
</div>
The above jquery works wells for every check and uncheck events of checkboxes and populating its values to textbox separated by comma, My issue is if someone manually enters some email separated by comma in the above textbox I want that value to be retained and not to be refreshed for the check and uncheck events of my check box. How can I achieve this?
The general technique that I would use to solve this is:
On every check or uncheck:
1. Split the list by comma into an array.
2. Gather all preset email values that are checked (you're doing this already).
3. Find every split value that isn't in the preset array, and set it aside.
4. Insert all your checked preset values, and then add in all the oddballs, or vice versa.
This doesn't preserve order, but it does retain any manually entered values. Retaining order could be done but would be a little more tricky.
You might also consider just having a separate "additional email" text box which would reduce the complexity of this and potentially make it more intuitive for the user.
Code:
function updateTextArea() {
var allVals = [];
var checkedVals = [];
$('#all input[type=checkbox]').each(function () {
allVals.push($(this).val());
});
$('#all :checked').each(function () {
checkedVals.push($(this).val());
});
var potentialOtherEmails = $("#txtbox").val().split(",");
var confirmedOtherEmails = [];
$(potentialOtherEmails).each(function(index,value) {
if ($.inArray(value, allVals) == -1) {
confirmedOtherEmails.push(value);
}
});
$("#txtbox").val($.merge(checkedVals,confirmedOtherEmails));
}
$(function () {
$('#all input').click(updateTextArea);
updateTextArea();
});
There you go....
$(function () {
txtbox = $("#txtbox");
var prevVal;
$("input[type='checkbox']").click(function() {
prevVal = txtbox.val();
if($(this).is(":checked"))
{
txtbox.val(prevVal + $(this).val() + ", ");
}
else
{
prevVal = prevVal.replace($(this).val()+", ", "");
txtbox.val(prevVal);
}
});
});
One note of caution on your existing code, you're querying the DOM too much (iterating over checkboxes on every check made), don't do that. Also, why you use document.getElementById when you have JQuery available? :-) this may not be a perfect solution, but works!!

Categories

Resources