Changing value separation from "," to "-" (JS/Jquery) - javascript

I received some Jquery code for an HTML checkbox. Essentially, when checked, the value of the checkbox is placed in an input box. When I uncheck the box, the value is cleared from the input. However, when you check multiple checkboxes, a "," separates the values. Is there a way to seperate the values by "-" instead of ","? I tried playing around with the code and it just breaks the code. I am fairly new to JS/Jquery so if it is a simple answer, I apologize. I can provide more information if needed. A working JSFiddle with "," is here: https://jsfiddle.net/m240Laka/25/
My code is located here:
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice");
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(",").filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join());
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join());
}
}
});
$none.on("change", function () {
var $this = $(this),
isThisChecked = $this.prop("checked");
if(isThisChecked){
$choice.prop({
disabled: true,
checked : false
});
$choiceDisplay.val("");
}else{
$choice.prop({disabled: false});
return false;
}
});

In the functions join() and split(), you need to pass in the delimiter you want, '-'. I suggest creating a local variable that you use, so it is easier to change this if needed.
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice"),
delimiter = '-';
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(delimiter).filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
}
});
Here is it in a jsfiddle.

In $.join() add the separator string parameter:
$choiceDisplay.val(choiceSelectionsArray.join("-"));
UPDATE:
add the same in $.split()
choiceSelectionsArray = $choiceDisplay.val().split("-")....

Related

How to make other JQuery run when a separate function runs?

I have the JS code below which filters based on checkboxes being checked or not (I don't think you need to see all the HTML because my question is rather simple/general, I think). All this code works fine, but I added a new function at the bottom (I noted it in the code) that simply has an uncheck all button for one of the sets of checkboxes (because there are like 30 checkboxes and I don't want the user to have to uncheck them all manually).
Anyway, the new script works properly too, except that the overall unrelated script that compares all checkboxes needs to run each time the new Uncheck All/Check All button is clicked.
Is there a simple way to make sure all the other JS runs when this new script is run?
I could be wrong, but I think I just need to somehow trigger this function inside the NEW FUNCTION:
$checkboxes.on('change', function() {
but am not sure how to do that.
ALL JS:
<script>
$(window).load(function(){
Array.prototype.indexOfAny = function(array) {
return this.findIndex(function(v) {
return array.indexOf(v) != -1;
});
}
Array.prototype.containsAny = function(array) {
return this.indexOfAny(array) != -1;
}
function getAllChecked() {
// build a multidimensional array of checked values, organized by type
var values = [];
var $checked = $checkboxes.filter(':checked');
$checked.each(function() {
var $check = $(this);
var type = $check.data('type');
var value = $check.data('value');
if (typeof values[type] !== "object") {
values[type] = [];
}
values[type].push(value);
});
return values;
}
function evaluateReseller($reseller, checkedValues) {
// Evaluate a selected reseller against checked values.
// Determine whether at least one of the reseller's attributes for
// each type is found in the checked values.
var data = $reseller.data();
var found = false;
$.each(data, function(prop, values) {
values = values.split(',').map(function(value) {
return value.trim();
});
found = prop in checkedValues && values.containsAny(checkedValues[prop]);
if (!found) {
return false;
}
});
return found;
}
var $checkboxes = $('[type="checkbox"]');
var $resellers = $('.Row');
$checkboxes.on('change', function() {
// get all checked values.
var checkedValues = getAllChecked();
// compare each resellers attributes to the checked values.
$resellers.each(function(k, reseller) {
var $reseller = $(reseller);
var found = evaluateReseller($reseller, checkedValues);
// if at least one value of each type is checked, show this reseller.
// otherwise, hide it.
if (found) {
$reseller.show();
} else {
$reseller.hide();
}
});
});
//NEW FUNCTION for "UNCHECK ALL" Button
$(function() {
$(document).on('click', '#checkAll', function() {
if ($(this).val() == 'Check All') {
$('input.country').prop('checked', true);
$(this).val('Uncheck All');
} else {
$('input.country').prop('checked', false);
$(this).val('Check All');
}
});
});
});
New button HTML for the new UNCHECK portion:
<input id="checkAll" type="button" value="Uncheck All">
I kept researching and discovered the trigger() function to handle this.
http://api.jquery.com/trigger/

Uncaught TypeError: Cannot read property 'prop' of undefined

I have 6 input checkboxes and if checkboxes are checked more than 3 the last one gets unchecked. For better understanding refer my previous question. Which is solved.
Now, I have another problem, Now 3 checkboxes are checked already by Math.random. On click of any unchecked checkbox. I'm getting error in console.
Uncaught TypeError: Cannot read property 'prop' of undefined
Fiddle Demo
code below:
var random_checked = $("input[type=checkbox]").get().sort(function(){
return Math.round(Math.random())-0.6; //so we get the right +/- combo
}).slice(0,3);
$(random_checked).prop('checked', true);
var checked = [];
$('input[type=checkbox]').change(function(e) {
var num_checked = $("input[type=checkbox]:checked").length;
if (num_checked > 3) {
checked[checked.length - 1].prop('checked', false);
checked.pop();
}
if($.inArray($(this), checked) < 0){
checked.push($(this));
}
});
You can try the below code
var checked = $('input[type=checkbox]:checked').map(function(){
return $(this);
}).get(); // First change
$('input[type=checkbox]').change(function(e) {
var num_checked = $("input[type=checkbox]:checked").length;
if (num_checked > 3) {
$(checked.pop()).prop('checked', false);// Second change
}
if($.inArray($(this), checked) < 0){
checked.push($(this));
}
});
DEMO FIDDLE
Changes Made
► Stored the currently checked elements to an array using
var checked = $('input[type=checkbox]:checked').map(function(){
return $(this);
}).get();
► $(checked.pop()) is used to select the last inserted element.
Why your code was not working?
As per you code var checked = []; will be empty at the initial stage. So checked[checked.length - 1] will become undefined.
You should push initial items in checked list.
$(random_checked).each(function(){
console.log($(this));
checked.push($(this));
});
https://jsfiddle.net/usx8Lkc5/18/
This one works, just simply adding lastChecked = random_checked[2]; so that your lastChecked is defined.
var random_checked = $("input[type=checkbox]").get().sort(function(){
var test = Math.round(Math.random())-0.6;
return test; //so we get the right +/- combo
}).slice(0,3);
$(random_checked).prop('checked', true);
lastChecked = random_checked[2];
var $checks = $('input:checkbox').click(function(e) {
var numChecked = $checks.filter(':checked').length;
if (numChecked > 2) {
alert("sorry, you have already selected 3 checkboxes!");
lastChecked.checked = false;
}
lastChecked = this;
});

On Checkbox click event, Unable to remove checked="checked' attribute

I have a Jquery Dialog box within my view, In this dialog box there is a UL LI list which is transformed to a treeview. I retain previous checkbox checked selection by adding the checked attribute in my HTML Text Writer helper. What I am trying to do is to remove the checked attribute once its un-checked. I am able to fire the event and get the value for instance true or false for check or uncheck but I am not able to scuccessfully remove the checked attribute if it was checked. The DOM still have the previous state of checked.
HTML Writer
InUl(() => locations.ForEach(location => InLi(() =>
{
var children = this.childrenRenderer(location);
bool childStatus = !(children != null && children.Count() > 0);
if (childStatus)
{
writer.AddAttribute("type", "checkbox");
writer.AddAttribute("value", urlRenderer(location));
writer.AddAttribute("id", htmlPrefix + urlRenderer(location));
writer.AddAttribute("onclick", "handleClick(this)");
if (keys != null)
{
if (keys.Contains(Convert.ToInt32(urlRenderer(location))))
{
writer.AddAttribute("checked", "checked");
}
}
writer.RenderBeginTag("input");
}
writer.Write(locationRenderer(location));
if (childStatus)
{
writer.RenderEndTag();
}
RenderLocations(children);
})));
JS Function
function handleClick(e) {
alert("Click, new value = " + e.checked);
var $this = $(this);
if (e.checked = false) {
$this.removeAttr('checked');
}
}
If I uncheck a checkbox, the following function still gives the old checkbox which is now unchecked:
$("#errorCodes input:checkbox:checked").each(function () {
var v = $(this).val();
a.push(v);
if (errorTextArea.length > 0) {
errorTextArea = errorTextArea + " | ";
}
errorTextArea = errorTextArea + v;
});
Try this:
function handleClick(e) {
alert("Click, new value = " + e.target.checked);
if (e.target.checked == false) {
e.target.removeAttr('checked');
}
}
You have a simple error in your code:
if (e.checked = false)
should read
if (e.checked == false)

Jquery validation not working properly?

I am trying to do required validation in a asp.net page.
I have multiple controls that will be hidden and displayed.
Controls like checkboxlist,dropdownlist,multiselectedlistbox.
I am using a css class called required attaching to all these controls to check the validation.
I am trying to check if each control has value or not but my code is checking each options with in each controls.
I am really not finding a way not a jquery expert just a novice...
Here is my code any ideas anyone please....
$("input[type='submit']").click(function () {
if ($(this).val() != 'Back') {
var names = [];
var info=" ";
$('.required input').each(function () {
var control = $(this);
if (control.is(':enabled')) {
names[$(this).attr('name')] = true;
}
});
$('.required option').each(function () {
var control = $(this);
if (control.is(':enabled')) {
names[$(this).attr('name')] = true;
}
});
for (name in names) {
var radio_buttons = $("input[name='" + name + "']");
if ((radio_buttons.filter(':checked').length == 0) ||(radio_buttons.filter(':selected').length == 0)) {
info += radio_buttons.closest("table").find('label').html()+"</br>";
}
}
if (info != " ") {
$("#validation_dialog p").html(info);
$("#validation_dialog").dialog({
title: "Validation Error!",
modal: true,
resizable: false,
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
return false;
}
}
});
here is a fiddle for it...
http://jsfiddle.net/bDmgk/35/
I think what you want is:
$(".required input[type='radio']:checked").each(function(){
});
instead of :
$(".required option").each(function(){ ... });
Hi I made some changes to your fiddle basically I checked for the inputs inside each column like this and then I added them to your names array.
Using
$('table.required:eq(0) input:checked')
I you can got all the inputs that are checked on the first column if the lenght of the array returned is 0 then no input is checked, i't the same procedure for the other ones.
An yes those input names are weird.
Check this fiddle
JSFiddle

Displaying a hidden text box when a particular option value selected

I am trying to make a hidden text-box visible when a particular option value is selected, It works when there are multiple options available obviously because it responds to onChange. How can I get it to work if that is the only option present, the first select box in my Example.
Js Fiddle - http://jsfiddle.net/8bm9R/
This is my Js function
function showOther(fieldObj, otherFieldID) {
var fieldValue = fieldObj.options[fieldObj.selectedIndex].value;
var otherFieldObj = document.getElementById(otherFieldID);
otherFieldObj.style.visibility = (fieldValue == 'other') ? '' : 'hidden';
return;
}
I've updated the JsFiddle:
Basically JsFiddle is misused, the function should be set to be wrapped in the header instead of 'onLoad'.
jsfiddle.net/8bm9R/2/
function showOther(fieldObj, otherFieldID)
{
var fieldValue = fieldObj.options[fieldObj.selectedIndex].value;
var otherFieldObj = document.getElementById(otherFieldID);
otherFieldObj.style.visibility = (fieldValue=='other') ? '' : 'hidden';
return;
}
Cheers
$("select").change(function() {
if($(this).val() == "expected_value") {
otherFieldObj.style.visibility = "visible"
}
else {
otherFieldObj.style.visibility = "hidden"
}
});

Categories