Create a dynamic link based on checkbox values - javascript

What I'm trying to achieve is this:
Default state of page = no checkboxes ticked, no link shown
User ticks one (or more) checkboxes
Link appears, dynamically generated from the checkbox values, in the following format: http://example.com/?subject=Products&checked=Blue,Green,Purple (where the selected checkbox values are "Blue", "Green" and "Purple")
Thus far, based on advice from another question (Using JavaScript to load checkbox Values into a string), I've been able to get the values in the proper format (as part of the required url) printed to console.log via a button:
$("button").on("click", function(){
var arr = []
$(":checkbox").each(function(){
if($(this).is(":checked")){
arr.push($(this).val())
}
})
var vals = arr.join(",")
var str = "http://example.com/?subject=Products&" + vals
console.log(str)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" id="selected" name="selected" value="Blue" class="products"> Blue<br>
<input type="checkbox" id="selected" name="selected" value="Green" class="products"> Green<br>
<input type="checkbox" id="selected" name="selected" value="Purple" class="products"> Purple
<br>
<button>button</button>
However, they're not loading dynamically based on the selected checkboxes (it requires you to press the button in order to generate the url) and the link hasn't been printed to the page for use by visitors (it's stuck in console.log, visible but not usable).
I've been advised that .change() might be the way to go here, in terms of generating the link dynamically. Something like: jQuery checkbox change and click event.
How can I merge the two approaches to achieve the result I'm looking for?

This would work to give you a url of
http://example.com/?subject=Products&checked=Blue,Green,Purple
(see below for a possibly better way):
$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
var vals = arr.join(",")
var str = "http://example.com/?subject=Products&checked=" + vals;
var link = arr.length > 0 ? 'Click me': '' ;
$('.link-container').html(link);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="mod-link" name="selected" value="Blue" class="products">Blue
<br>
<input type="checkbox" class="mod-link" name="selected" value="Green" class="products">Green
<br>
<input type="checkbox" class="mod-link" name="selected" value="Purple" class="products">Purple
<br>
<div class="link-container"></div>
However
I would do it a bit different.
I would opt for the following url structure:
http://example.com/?subject=Products&checked[]=Blue&checked[]=Green&checked[]=Purple
When that is recieved by PHP, checked will be an array like ['Blue','Green','Purple'] instead of a string like 'Blue,Green,Purple'
$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
var vals = 'checked[]=' + arr.join("&checked[]=")
var str = "http://example.com/?subject=Products&" + vals;
var link = arr.length > 0 ? 'Click me': '' ;
$('.link-container').html(link);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="mod-link" name="selected" value="Blue" class="products">Blue
<br>
<input type="checkbox" class="mod-link" name="selected" value="Green" class="products">Green
<br>
<input type="checkbox" class="mod-link" name="selected" value="Purple" class="products">Purple
<br>
<div class="link-container"></div>

I believe that you were on the right track, if I understood your question correctly. I added the change event on you checkboxes as you suggested. Try the modified code below.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" name="selected" value="Blue" class="products"> Blue<br>
<input type="checkbox" name="selected" value="Green" class="products"> Green<br>
<input type="checkbox" name="selected" value="Purple" class="products"> Purple
<br>
<span class="link"></span>
JavaScript
$("input[type=checkbox]").on("change", function(){
var arr = []
$(":checkbox").each(function(){
if($(this).is(":checked")){
arr.push($(this).val())
}
})
var vals = arr.join(",")
var str = "http://example.com/?subject=Products&checked=" + vals
console.log(str);
if (vals.length > 0) {
$('.link').html($('<a>', {
href: str,
text: str
}));
} else {
$('.link').html('');
}
})
Working CodePen
Your button is no longer being used. Is this what you were looking for?

Related

Add/Remove values to field from checkbox values in Javascript

I have two fields: one is a checkbox (built with Scala), one is an input/text field. I am trying to add and remove values from the checkbox to the input field. I am trying to take multiple values and string together with a comma.
Here are my HTML fields:
<div class="column column1">
#for(service <- servicesList) {
<label><input type="checkbox" name="selectServices" value=#service.name><span>#service.name</span></label>
}
</div>
<input name="services" id="services">
I am using jQuery in a tag to try to record the onchange event:
$(document).ready(function(){
var $services = $('#services');
var $selectServices = $('#selectServices');
$selectServices.change(function(){
for (var i = 0, n = this.length; i < n; i++) {
if (this[i].checked) {
$services.val($services.val() + this[i].value);
}
else {
$services.val($services.val().replace(this[i].value, ""));
}
}
});
});
However, it seems that this will not "fire" when checking and unchecking the checkbox. I do not receive any errors or messages, so I am guessing it is not working or the code is incorrect.
I appreciate the help!
Try this example, you don't have to search and replace all the time, just set a new value:
$(function() {
$('input[name=selectServices]').on('change', function() {
$('#services').val($('input[name=selectServices]:checked').map(function() {
return this.value;
}).get());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="column column1">
<label>
<input type="checkbox" name="selectServices" value='1'><span>1</span>
</label>
<label>
<input type="checkbox" name="selectServices" value='2'><span>2</span>
</label>
<label>
<input type="checkbox" name="selectServices" value='3'><span>3</span>
</label>
<label>
<input type="checkbox" name="selectServices" value='4'><span>4</span>
</label>
</div>
<input name="services" id="services">
does the $(function() {} go into the $(document).ready(function(){}?
No, it is short-hand or equivalent for the same.
This is just an addition on #Halcyon his answer so you can create a nicer list, in stead of the replace method. #Halcyon is most definitely the correct answer why your check boxes aren't working. This is just a better solution handling values.
$(document).ready(function(){
var $services = $('#services');
var $selectServices = $('.selectServices');
$selectServices.change(function(){
updateServices();
});
function updateServices() {
var allVals = [];
$('.selectServices:checked').each(function() {
allVals.push($(this).val());
});
$services.val(allVals);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="column column1">
<label><input class="selectServices" type="checkbox" name="selectServices[]" value="Foo"><span>Foo</span></label>
<label><input class="selectServices" type="checkbox" name="selectServices[]" value="Bar"><span>Bar</span></label>
<label><input class="selectServices" type="checkbox" name="selectServices[]" value="FooBar"><span>FooBar</span></label>
</div>
<input name="services" id="services">
$('#selectServices') selects by id, there are no elements with that id. Ids must be unique so you can't use them in this case. I also wouldn't recommend using name because input elements should have unique names. You can use class:
<label><input type="checkbox" class="selectServices" ...
Then use .selectServices in jQuery. And:
var $selectServices = $('.selectServices');
$selectServices.change(function(){
if (this.checked) {
$services.val($services.val() + this.value);
} else {
$services.val($services.val().replace(this.value, ""));
}
});
Your code will fire if you add ID's to your inputs:
<input type="checkbox" name="selectServices" id="selectServices" value="" />
and
<input name="services" id="services" type="text" />

Repeative values occur in Autocomplete jquery

I am working in ASP.NET Project.My task is to Prevent the repative values occured in Textbox.Textbox is bound with autocomplete and appending text from checkboxlist as like in the below picture
! https://drive.google.com/file/d/0B5OPwgmPG6QpTHBTdVlFaldRaEE/view?usp=sharing
After i appended the content from checkbox list to textbox means it is repeating value,if i typed it inital time it won't.And my task is to show unique values based on the textbox content.
My project files are in the below link..please help me out guys
https://drive.google.com/file/d/0B5OPwgmPG6QpS3NMNElGN2k4RzQ/view?usp=sharing
Based on my answer I gave you in the other thread (https://stackoverflow.com/a/28828842/4569271) I extended my solution to only display unique values:
$(function() {
$('input[type="checkbox"]').change(function() {
// Reset output:
$("#output").html('');
// remeber all unique values in this array:
var tmpArray = new Array();
// Repeat for all checked checkboxes:
var checkboxes = $('input[type="checkbox"]:checked').each(function() {
// Get value from checkbox:
var textToAppend = $(this).val();
// Check if value from checkbox was added already:
if (jQuery.inArray(textToAppend, tmpArray) == -1) {
// add entry to array so it will be not added again:
tmpArray.push(textToAppend);
var existingText = $("#output").html();
// Append seperator (';') if neccessary:
if (existingText != '') {
existingText = existingText + ";";
}
// Print out append value:
$("#output").html(existingText + textToAppend);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select:</h2>
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<h2>Output:</h2>
<div id="output"></div>
Based on your description, I am not sure if this is the solution you were looking for? But maybe it helps.

How to show jquery dialog with radio buttons when checkbox is checked and post value in textbox

I have 41 checkboxes like this
HTML
<input id="1" type="checkbox" onclick="updatebox()" />
<input id="2" type="checkbox" onclick="updatebox()" />
<input id="3" type="checkbox" onclick="updatebox()" />
<input id="4" type="checkbox" onclick="updatebox()" />
Javascript
<script type="text/javascript">
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
if(document.getElementById('1').checked) {values.push("1");}
if(document.getElementById('2').checked) {values.push("2");}
if(document.getElementById('3').checked) {values.push("3");}
if(document.getElementById('4').checked) {values.push("4");}
textbox.value = values.join(", ");
}
</script>
When checkbox is checked the value is posted in textbox,
now what i want is when the user clicks the checkbox the jquery dialog popups and the user will have two radio buttons with Male or Female options along with ok button so when the user will click on ok the value should be posted on textbox depending on selection M for male F for female along with number like 1M or 1F, 2M or 2F and so on.
P.S user can select multiple checkboxes.
Thanks You!
Here is something that does what you want. HTML:
<body>
<form id="form">
<input id="1" type="checkbox" /> 1
<input id="2" type="checkbox" /> 2
<input id="3" type="checkbox" /> 3
<input id="4" type="checkbox" /> 4
...
<input id="10" type="checkbox" /> 10
...
<input id="41" type="checkbox" /> 41
<input id="list" />
</form>
<div id="prompt" style="display:none;" title="Gender">
<form>
<input type="radio" name="gender" id="radio" value="male" />
<label for="radio">Male</label>
<input type="radio" name="gender" id="radio2" value="female" />
<label for="radio2">Female</label>
</form>
</div>
</body>
The JavaScript:
$(function() {
var form = document.getElementById("form");
var textbox = document.getElementById("list");
var $prompt = $("#prompt");
// We record what is currently checked, and the user's answers in this `pairs` object.
var pairs = [];
// Listen to `change` events.
$("input[type='checkbox']", form).on('change', function (ev) {
var check = ev.target;
if (check.checked) {
// Checked, so prompt and record.
$prompt.dialog({
modal: true,
buttons: {
"Ok": function() {
var gender = $prompt.find("input[name='gender']:checked")[0];
var letter = {"male":"M", "female":"F"}[gender.value];
pairs[check.id] = '' + check.id + letter;
$( this ).dialog( "close" );
refresh();
}
}
});
}
else {
// Unchecked, so forget it.
delete pairs[check.id];
refresh();
}
function refresh() {
// Generate what we must now display in the textbox and refresh it.
// We walk the list.
var keys = Object.keys(pairs);
var values = [];
for (var i = 0, key; (key = keys[i]); ++i) {
values.push(pairs[key]);
}
textbox.value = values.join(", ");
}
});
});
Here is a jsbin with the code above.
Salient points:
This code adds the event handlers using JavaScript rather than use onclick in the HTML. It is not recommended to associated handlers directly in the HTML.
It listens to the change event rather than click. Some clicks can sometimes not result in a change to an input element.
It uses $.dialog to prompt the user for M, F.
The refresh function is what recomputes the text field.
It keeps a record of what is currently checked rather than requery for all the check boxes when one of them changes.
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
for (var i = 1; i <= 41; ++i) {
var id = '' + i;
if (document.getElementById(id).checked) {
var gender = prompt('Male (M) or female (F)?');
values.push(gender + id);
}
}
textbox.value = values.join(", ");
}
A few things to note:
I got rid of all that code repetition by simply using a for loop from 1 to 41.
I also fixed the strange indentation you had there.
You may want to use a method of getting user input other than prompt, but it'll work the same way.
(If you're going to keep using prompt, you might also want to add input validation as well to make sure the user didn't input something other than M or F.)

How to create javascript array based on user input using jQuery

I've dynamically loading check box fields, how can I send those to server based on user selection.
For example I've following doc,
<label>Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<label>Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />
Suppose if user selected first two values for each of them, then I need to send like
response[0][0]=199; // Id
response[0][1]=['Apple','Mango']; //values
response[1][0]=200
response[1][1]=['Red','Blue'];
I've tried some approaches suggested in existing posts but failed to implement how I want.
You can make some minor changes in the html then use .map()
<label class="set" data-id="199">Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<label class="set" data-id="200">Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />
then
var array = $('.set').map(function () {
var $this = $(this),
id = $this.data('id'),
array = [id];
array.push($('input[name="set_' + id + '\\[\\]"]').filter(':checked').map(function () {
return this.value;
}).get())
return [array]
}).get()
Demo: Fiddle
Yet another solution:
<lable>Set1</lable>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<input type="button" value="check" class="js-submit">
Js:
$(".js-submit").on("click", function(){
var a = $("input[type='checkbox']:checked");
var values = {};
a.each(function(){
var value = $(this).val();
var name = $(this).attr("name");
if(!values[name]) values[name] = [];
values[name].push(value)
});
console.log(values)
});
Demo
To expand on my comment a little, here's how I'd do this... given that you're sending this as an ajax request, I'd still wrap these elements in a form element, and use that as a starting-point to build the object we'll be sending...
var myForm = document.getElementById('formID').elements,//get all input nodes
data = {},temp;
for (var i=0;i<myForm.length;++i)
{
temp = myForm.item(i).name.replace(/[[]]/g,'');//replace square brackets
if (!data[temp])
data[temp] = [];//create array if key does not exist
if (myForm.item(i).checked)//for checkboxes
data[temp].push(myForm.item(i).value);
}
That's the basic setup. If you want, you can add checks and further tailor this, so you can deal with various types of input fields, but in essence, it'll boil down to this.
You might also want to use Array.prototype.forEach on the myForm.elements NodeList, and use a callback to keep your code nice and clean.
Here's an example of a slightly more usable version of the same code:
btn.addEventListener('click', function()
{
var data = {};
Array.prototype.forEach.call(frm.elements, function(item)
{
var temp;
if (item === btn) return;//don't includ the button element
if (item.type === 'checkbox' && !item.checked ) return;//not checked, ignore
if (item.name.match(/[[]]/))
{
temp = item.name.replace(/[[]]/g, '');
if (!data[temp]) data[temp] = [];//if property does not exist, make an array
data[temp].push(item.value);
return;
}
//normal elements:
data[item.name] = item.value;
});
//ajax request using data variable goes here!
console.log(data);
},false);
And here's the fiddle of it
First of all thanks for all who have given answers to this question. I've derived my own solution for this issue but it is not possible without your help, especially this
var checkBoxArray = {};
$.each($("input[name^='set_'][type='checkbox']:checked"), function(i, item) {
var Id = item.name.replace(/^(set_)|[\[\]]/g, "");
var value = $(item).val();
if(!checkBoxArray[Id])
checkBoxArray[Id] = [];
checkBoxArray[Id].push(value)
});
$.map(checkBoxArray, function(value, index) {
reponse.push([index, value]);
});
Its worked for me, suggest if anything not proper in above code snippet.

How to define textfield and radio button listeners in JavaScript

So for a class project I have to make this simple calculator, which was very easy to do. However, I'm required to define my event listeners in JavaScript instead of using something like:
onclick="compute()"
But I need the result of my calculator to update whenever I change a value in my field or select any of the radio buttons. How can I do this? The code I have now is not working.
<script>
function compute(){
var functionSelected = document.getElementsByName("function");
var valueOne = Number(document.getElementById("fielda").value);
var valueTwo = Number(document.getElementById("fieldb").value);
var ans = 0;
if(functionSelected[0].checked){
ans = (valueOne+valueTwo);
}
if(functionSelected[1].checked){
ans = (valueOne-valueTwo);
}
if(functionSelected[2].checked){
ans = (valueOne*valueTwo);
}
if(functionSelected[3].checked){
ans = (valueOne/valueTwo);
}
if(ans>=9007199254740992){
document.getElementById("solution").textContent = "ERROR NUMBER TO LARGE TO BE COMPUTED";
}
else{
document.getElementById("solution").textContent = "Equals: " + ans;
}
}
document.getElementById("fielda").addEventListener("change", compute(), false);
document.getElementById("fieldb").addEventListener("change", compute(), false);
document.getElementByName("function").onclick = compute();
</script>
</head>
<body>
<p>
<input type="number" id="fielda"/><br />
<input type="number" id="fieldb"/><br />
<label><input name="function" type="radio" value="add"/> Add</label><br />
<label><input name="function" type="radio" value="subtract"/> Subtract</label><br />
<label><input name="function" type="radio" value="multiply"/> Multiply</label><br />
<label><input name="function" type="radio" value="divide"/> Divide</label><br />
</p>
<p>
<output id="solution">Solution Will Appear Here</output>
</p>
</body>
You can use
<select ... onchange="javascript:compute();">
There are a lot of events that you can use in response to different events depending on the control.
They are named onmouseover, onclick, onchange, etc. and you can assign a javascript function to each one if you want.
Another alternative is to use you following syntax:
document.getElementById("id_of_select_control").onchange = function() {
// your code here
}
Or if you use jQuery in your project, something like this:
$("#id_of_select_control").change(function() {
// your code here
});

Categories