Remove specific characters from string jquery [duplicate] - javascript

This question already has answers here:
jQuery: Add values of checkboxes to input text field
(4 answers)
Closed 4 years ago.
OK, So although it seems normal substring or replaces solution answer it is quite complex for me.
I have 3 checkboxes
A,B,C
and one text box
Now, when user select any checkbox the value of checkbox appends into textbox i.e. Fist he selects A -> textbox will be appended by A
Then if selects B -> textbox value will be A, B and so on.
i have done it already.
Now the problem is for unchecking.
If the value of textbox is A,B,C i.e. the selected checkboxes are A,B,C and if user deselects the B then the value should be A,C and then again deselects the c then the value should be A.
I have tried multiple ways but don't work for all conditions, sometimes it becomes A, C or A, B
Any solution?
Thank you in advance :)

You can simply recreate the list on change of a box
let els = [...document.getElementsByClassName('check')];
els.forEach(e => e.addEventListener('change', () => {
document.getElementById('foo').value = els.filter(x => x.checked).map(x => x.value).join();
}))
.flex {
display: flex;
flex-direction: column;
}
<div class="flex">
<input id="foo" />
<label><input type="checkbox" class="check" value="A"/>A</label>
<label><input type="checkbox" class="check" value="B"/>B</label>
<label><input type="checkbox" class="check" value="C"/>C</label>
</div>

Try this:
1) On each checkbox click/unclick get the value of all checked checkboxes. (for example ['A', 'B'])
2) Generate the new string with join the values . ['A', 'B'].join(',') // returns 'A,B'
3) Set the textbox with the new string
If you need code you can submit your current code.

Here's what I came up with, without knowing how you're tracking what's checked or not, it's a data driven approach.
var checked = [];
function updateValue() {
$('#selected').val(checked.toString());
}
$('[type=checkbox]').click(function(e) {
var value = e.target.value;
if(e.target.checked) {
checked.push(value);
} else {
checked.splice(checked.indexOf(value), 1);
}
updateValue();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="A">A<br>
<input type="checkbox" value="B">B<br>
<input type="checkbox" value="C">C<br>
<input type="text" id="selected">

$(function() {
const valArray = []; // our value array here what gonna show in textarea
/**
- on change check if checkbox checked or not
- if checked push value of checkbox to array
if not search in our array "valArray" and get it's index then remove it
- change textarea value with the new array "valArray"
*/
$('.checkboxes input').on('change', function(e) {
const $thisVal = $(this).val(),
isChecked = $(this).is(':checked');
if (isChecked) {
valArray.push($thisVal);
} else {
const searchOnThisVal = valArray.find(item => $thisVal === item),
getTheIdx = valArray.indexOf(searchOnThisVal);
valArray.splice(getTheIdx, 1);
}
$('.textarea').empty();
$('.textarea').text(valArray);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkboxes">
<label>
<input type="checkbox" value="a">
the checkbox A.
</label>
<label>
<input type="checkbox" value="b">
the checkbox B.
</label>
<label>
<input type="checkbox" value="c">
the checkbox C.
</label>
</div>
<textarea class="textarea" placeholder="your choice..."></textarea>
this should work in your case using jQuery API

Related

Uncheck checkbox when I check another one

Hey I have two issues with this following code.
First of all when I check the checkbox number 3 it automatically checks number 2, I only want that if I check it my self (Like when I check checkbox number 2).
The second issue is I can't uncheck a checkbox after checking it.
var cbs = document.getElementsByName("test");
function demo(obj) {
var hzp = cbs[1];
var ht = cbs[2];
for (var i = 0; i < cbs.length; i++) {
if(cbs[i].value == hzp.value || cbs[i].value === ht.value) {
if(cbs[i].value == obj.value) {
if(cbs[i].checked && hzp.checked || ht.checked) {
hzp.checked = true;
ht.checked = true;
}
}
}
cbs[i].checked = false;
}
obj.checked = true;
}
checkbox 1 <input type="checkbox" name="test" id="demo1" value="demo01" onClick="demo(this)">
checkbox 2 <input type="checkbox" name="test" id="demo2" value="demo02" onClick="demo(this)">
checkbox 3 <input type="checkbox" name="test" id="demo3" value="demo03" onClick="demo(this)">
checkbox 4 <input type="checkbox" name="test" id="demo" value="demo04" onClick="demo(this)">
e.target.value==cbs[0].value ?
if clicked input has value of demo01
cbs[3].checked=false
set demo04 checked to false
: e.target.value==cbs[3].value
else if clicked input has value of demo04
? cbs[0].checked=false
set demo01 checked to false
: null
else, nothing...
var cbs = document.getElementsByName("test")
cbs.forEach( test => {test.addEventListener("change", (e) => {
e.target.value==cbs[0].value ? cbs[3].checked=false : e.target.value==cbs[3].value ? cbs[0].checked=false : null
})
})
checkbox 1 <input type="checkbox" name="test" id="demo1" value="demo01" >
checkbox 2 <input type="checkbox" name="test" id="demo2" value="demo02">
checkbox 3 <input type="checkbox" name="test" id="demo3" value="demo03">
checkbox 4 <input type="checkbox" name="test" id="demo" value="demo04">
Look closely - this is not jQuery.
This gets your bigger job simplified - that of making the checkboxes work like radio buttons. Now, you should be able to quite easily add logic to make it do the rest of what you want.
The basic idea is to:
a. Trap when any checkbox is clicked
b. Store the checked checkbox value
c. Cache the checkbox itself (so we can turn it back on)
d. Uncheck ALL checkboxes
e. Re-check the one the user just checked.
f. Update div / variable with the stored value
Now, just add some additional (e.g. storedVal) variables to keep track of additional checkboxes.
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
var storedVal = '';
$$('input').forEach((el) => {
el.addEventListener('click', function(e){
storedVal = e.target.value;
let ckcb = e.target;
uncheckAll();
ckcb.checked = true;
console.log(storedVal);
$('#msg').innerText = storedVal;
});
});
const uncheckAll = () => {
$$('input').forEach((el) => {
el.checked = false;
});
}
#msg{
position:absolute;
top:70px;
right:30px;
font-size:2rem;
padding:10px;
background:wheat;
}
checkbox 1 <input type="checkbox" name="test" id="demo1" value="demo01">
checkbox 2 <input type="checkbox" name="test" id="demo2" value="demo02">
checkbox 3 <input type="checkbox" name="test" id="demo3" value="demo03">
checkbox 4 <input type="checkbox" name="test" id="demo" value="demo04">
<div id="msg"></div>

get array of checkboxes checked, and only if seletced in a specific order, then go to URL

First time asking here. I tried a number of topics for this, and I currently use a code for checkboxes, but it's for gathering into a mailform and sending to me via php. I can't seem to find exactly what I need for the following scenario.
I am reworking some Flash puzzles to be all html and javascript (or jquery). One puzzle requires the player to enter a code (to open a safe). In Flash they clicked buttons with code symbols on them, so I thought, Checkboxes displayed as images could work...
I have 9 checkboxes. Each has a value from 1 to 9. In the layout they are mixed up (they are not positioned on the page in sequential order) and I use images to represent the checkboxes.
I want to find out if all the boxes are selected, and if they are selected in the exact order of 1-9.
If the checkboxes are checked in the correct order according to their value (1,2,3,4,5,6,7,8,9) then on clicking the Submit button, the player is taken to the next webpage.
I can also do this with names or Ids, whatever works. Or php. I was hoping to keep it simple, because I am not savvy with the javvy. I probably know enough to be dangerous to myself and others :)
Thanks in advance for any help, or links to a topic that could point me in the right direction.
Here's my html code.
<form name="checklist" method="post" action="My-Page.php">
<label>
<input type="checkbox" value="8">
<img src="btn_8.png"></label>
<label>
<input type="checkbox" value="3">
<img src="btn_3.png"></label>
<label>
<input type="checkbox" value="9">
<img src="btn_9.png"></label>
<label>
<input type="checkbox" value="2">
<img src="btn_2.png"></label>
<label>
<input type="checkbox" value="5">
<img src="btn_5.png"></label>
<label>
<input type="checkbox" value="4">
<img src="btn_4.png"></label>
<label>
<input type="checkbox" value="7">
<img src="btn_7.png"></label>
<label>
<input type="checkbox" value="1">
<img src="btn_1.png"></label>
<label>
<input type="checkbox" value="6">
<img src="btn_6.png"></label>
<input type="submit" value="Open">
</form>
Here's the js I found that gets the values, but I don't know how to make it get the values in that specific order, and then go to a URL, or alert the user to an error.
var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
Update. I struggled with this, and finally asked a friend to help. What took me 8 days, he did in like 1 hour, from scratch.
I do appreciate those who took time to give me some hints, and this site is great for learning.
As you didn't share code , I will not help you fix it. I can give you some hints and you can try to implement that.
Call onClick function on each checkbox selection.
Create an array and push the selected checkbox's values into it.
// example: checkedArr = [1,2,3,4];
maintain a final order of values with another array
// expectedArr = [1,2,3,4];
Deep compare those 2 arrays and depending on their result, proceed with your business logic.
Comparing two array with their order
var is_same_arr = (checkedArr.length == expectedArr.length) && checkedArr.every(function(element, index) {
return element === expectedArr[index];
});
Here is one way to do it in JavaScript. You maintain a selected array that you either add to or remove items from as the checkboxes are clicked. Then, when the form is submitted, you do a couple checks: first you see if all boxes have been checked. Next, you see if all of the numbers in the selected array are in order.
const form = document.querySelector("#form");
let selected = [];
const numberOfCheckboxes = document.querySelectorAll("#form input").length;
form.addEventListener("click", function(e) {
if (e.target.nodeName !== "INPUT") return;
if (e.target.checked) {
selected.push(parseInt(e.target.value));
} else {
selected = selected.filter(el => el != e.target.value);
}
})
function check(e) {
console.log(selected);
if (selected.length !== numberOfCheckboxes) {
e.preventDefault();
alert("You didn't select all the boxes");
}
const inOrder = selected.every((el, i, arr) => i === 0 || el === arr[i-1] + 1);
if (!inOrder) {
e.preventDefault();
alert("Wrong order!");
}
}
<form id="form" onsubmit="return check(event)">
<label>
<input type="checkbox" value="1" /> 1
</label>
<label>
<input type="checkbox" value="2" /> 2
</label>
<label>
<input type="checkbox" value="3" /> 3
</label>
<button>submit</button>
</form>

How to get the value of checkboxes in the order they are selected?

hope you can help me :)
I have this code to get the value of the checkboxes:
function check() {
var Input = Array.prototype.slice.call(document.querySelectorAll(".checkboxes:checked")).map(function(el) {
return el.value;
}).join(',')
document.getElementById('output2').innerHTML = Input;
return false;
}
I want that the output is in the order I selected the checkboxes. Is there a way to get them in correct order?
You can set the timestamp to them when they are changed (comments inline)
var allCheckboxes = document.querySelectorAll("input[type='checkbox'][data-name]");
//bind the event to set time value on change
[...allCheckboxes].forEach(s => s.addEventListener("change", function(e) {
e.currentTarget.timeval = new Date().getTime();
}));
document.querySelector("button").addEventListener("click", check);
function check() {
var output = [...allCheckboxes]
.filter(s => s.checked) // filter out non-checked
.sort((a, b) => a.timeval - b.timeval) //sort by timeval
.map(s => s.getAttribute("data-name")).join(","); //fetch only data-name for display
document.getElementById('output').innerHTML = output;
}
Check 1 <input type="checkbox" data-name="check1"> <br/> Check 2 <input type="checkbox" data-name="check2"> <br/> Check 3 <input type="checkbox" data-name="check3"> <br/> Check 4 <input type="checkbox" data-name="check4"> <br/> Check 5 <input type="checkbox"
data-name="check5"> <br/>
<button>check</button>
<div id="output"></div>
You can set an array and save the values as they are selected.
You can achive this by giving each chcekbox an event listener.
In the event listener you add an if to validate if the click event was when checked and then add them to your list/array.
Hope this helps :)
var checks = document.querySelectorAll('input[type=checkbox]');
var order = [];
for(var i=0; i<checks.length;i++){
checks[i].addEventListener("click", function(){
if(this.checked)
order.push(this.value);
})
}
<input type="checkbox" value="A">A
<input type="checkbox" value="B">B
<input type="checkbox" value="C">C
<input type="checkbox" value="D">D
<br>
<button onclick="console.log('Order: '+order)">Check order</button>
You can add a data-id attribute to each section. And when you click on one checkbox, change the attribute values of each checkbox to a serial number. To do this, it's easier to use jquery
You could use a Set and add or delete depending of the checked state of the check box.
Set returns the items in insertation order.
var checks = document.querySelectorAll('input[type=checkbox]'),
order = new Set,
i
for (i = 0; i < checks.length; i++) {
checks[i].addEventListener("click", function() {
order[['delete', 'add'][+this.checked]](this.value);
});
}
<input type="checkbox" value="A">A
<input type="checkbox" value="B">B
<input type="checkbox" value="C">C
<input type="checkbox" value="D">D
<br>
<button onclick="console.log('Order: '+[...order])">Check order</button>

Javascript: How can I get all value of selected checked checkboxes, push to an array then put in in a input HTML element?

I have a list of 50 checkboxes. If users check some of them, how can I get all values of the selected ones and push them into an array then place it in a hidden text element?
Can I use the same name for all checkboxes? or I must use different name for each of them?
<input type="checkbox" name="bulk_id[]" value="1"/>
<input type="checkbox" name="bulk_id[]" value="2"/>
<input type="checkbox" name="bulk_id[]" value="3"/>
<input type="checkbox" name="bulk_id[]" value="4"/>
<input type="checkbox" name="bulk_id[]" value="5"/>
...
Thank you.
You tagged your question with jquery, so i'll assume you are using it.
You select checkbox with input[type=checkbox] and use the subclass :checked to filter checked ones
1- get all checked boxes in an array
var selectedValues =[]
$('input[type=checkbox]:checked').each(function(i,e){
selectedValues.push( $(e).attr('value') )
})
2- append the content of this array in a hidden input (separated by ,)
$('#yourhiddenID').val( selectedValues.join(',') );
In this solution the name of your checkboxes does not matter.
Put your checkboxes in a container for a better selection :
$('#yourCheckboxContainerID input[type=checkbox]:checked')
so you have to get all checkboxes you have
var checkboxes = document.getElementsByName("bulk_id[]");
var arrayVal = [];
for (var i= 0; i<checkboxes.length;i++)
{
if (checkboxes[i].checked === true)
{
arrayVal.push(checkboxes[i].value);
}
}

Javascript - If no radio buttons are selected, check the first one

I'm a beginner in JavaScript. I have several radio buttons on my dynamic page and I want to create a script to make the following:
HTML:
<input type="radio" id="elemainfoto">
<input type="radio" id="elemainfoto">
<input type="radio" id="elemainfoto">
JavaScript:
var radio = '#elemainfoto',
if(radd.value == 0) {
radd.checked the first radio element,
} else {
keep the way it is,
}
If none of the radio elements are marked, mark the first compulsory.
I your expectation is that the first item get selected by default, then you should use HTML and not javascript for that and please note that you should not use two HTML elements with the same id in your case you should either replace by a class and/or add unique Ids for elements.
<input type="radio" class="elemainfoto" id="item1" checked>
<input type="radio" class="elemainfoto" id="item2">
<input type="radio" class="elemainfoto" id="item3>
Updated the answer based on RobG comment.
Something like this in pure JS (I changed ids to classes id should be unique):
var radio = document.querySelectorAll('.elemainfoto'),
checked = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
checked = true;
break;
}
}
if (!checked) {
radio[0].checked = true;
}
else {
alert('something is checked')
}
A little shorter with jQuery:
var $radio = $('.elemainfoto');
if (!$radio.filter(':checked').length) {
$radio[0].checked = true;
}
else {
alert('something is checked')
}
using 'id' attribute in html with the same value more than once is invalid, you should use "name" for an input.
HTML:
<input type="radio" name="elementinfoto" value="1" />
<input type="radio" name="elementinfoto" value="2" />
<input type="radio" name="elementinfoto" value="3" />
JavaScript:
var radio = document.getElementsByName('elementinfoto'); // get all radio buttons
var isChecked = 0; // default is 0
for(var i=0; i<radio.length;i++) { // go over all the radio buttons with name 'elementinfoto'
if(radio[i].checked) isChecked = 1; // if one of them is checked - tell me
}
if(isChecked == 0) // if the default value stayed the same, check the first radio button
radio[0].checked = "checked";
example: http://jsfiddle.net/yxm4N/2/
A radio button group is formed by giving radio buttons the same name. An ID is optional and usually not necessary. If an ID is provided, each should have a different value. And the buttons should have a value so that there's a point to their existence.
To have one button selected by default, simply set the chosen button's checked attribute:
<form id="foo">
<input type="radio" name="elemainfoto" valu="0" checked>0<br>
<input type="radio" name="elemainfoto" valu="1">1<br>
<input type="radio" name="elemainfoto" valu="2">2<br>
<input type="reset">
</form>
Now if no other button is selected, or the form is reset, one button will be selected. Note that if you do not set a button as the default selected, then once a user checks a button, the only way to deselect it is to select a different radio button in the same group, or use a reset button (if provided).
If you want to set the default checked button in script, there are a couple of options. One is:
var buttons = document.getElementsByName('elemainfoto');
buttons[0].defaultChecked = true;
If you really want to check if one is selected, add a button like the following to the form:
<input type="button" value="Check buttons" onclick="checkButtons(this);">
Then the checkButtons function can be:
function checkButtons(el) {
var buttons;
var form = el && el.form;
if (form) {
buttons = form.elemainfoto;
for (var i=0, iLen=buttons.length; i<iLen; i++) {
// If a button is checked, return its value
if (buttons[i].checked) {
return buttons[i].value;
}
}
}
// Otherwise, try to check the first one and return undefined
buttons && buttons[0].checked;
}
you need to know how to use radio element. Id is unique in html page. you should assign same name for each radio element.
<input type="radio" name="elemainfoto" id="first" value="1" />
element 1
<input type="radio" name="elemainfoto" id="second" value="2" />
element 2
<input type="radio" name="elemainfotor" id="thrid" value="3" />
element 3
if you want to check the first radio button as default, set it in input tag attribute.
<input type="radio" name="elemainfoto" id="first" value="1" checked="true"/>
element 1
or you can do it with javascript also,
$("input:radio[name=elemainfoto]:first").attr('checked', true);
you can perform action for each radio button click, to know which item is checked
$(function(){
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
alert($(this).val());
}
});
});
if you want to perform a separate action for each radio button, try this below code
$(function () {
$('input[type="radio"]').click(function () {
if ($(this).is(':checked')) {
if ($(this).val() == '1') alert('first radio element is checked');
if ($(this).val() == '2') alert('second radio element is checked');
if ($(this).val() == '3') alert('third radio element is checked');
}
});
});
SEE THIS FIDDLE DEMO
Instead of selecting the first one, I prefered to use null
const radio = document.querySelectorAll('.timescale');
let timescale;
if (radio.checked) {
timescale = $('input[name=timescale_radio_buttons]:checked').val()
} else timescale = null;
You can write it like this with less code
HTML
<input type="radio" name="elementinfoto" value="1" />
<input type="radio" name="elementinfoto" value="2" />
<input type="radio" name="elementinfoto" value="3" />
JavaScript
const fields = document.getElementsByName('elementinfoto');
const value = fields.filter(el => el.checked).shift()?.value || null;
if(!value) {
fields.shift().checked = true;
}
You can replace the function shift() by [0] to get the first element if you prefer

Categories

Resources