Create an array of selected radio button values - javascript

I have few radio buttons:
<input type="radio" value="####.###/resources/videos/7.mp4">
<input type="radio" value="####.###/resources/videos/8.mp4">
<input type="radio" value="####.###/resources/videos/9.mp4">
How can I make an array containing the selected values like following:
var videos = ["./resources/videos/7.mp4",
"./resources/videos/1.mp4",
"./resources/videos/2.mp4",
"./resources/videos/3.mp4"];

Onclick push the value of radio in array
var arr=[];
$('input').click(function(){
arr.push("."+$(this).val().split('####.###')[1])
console.log(arr);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" value="####.###/resources/videos/7.mp4">Video1
<input type="radio" value="####.###/resources/videos/8.mp4">Video2
<input type="radio" value="####.###/resources/videos/9.mp4">Video3

I would add a change event listener, that checks if the input got checked or unchecked and would add it or remove it from the list.
var originalVideoList = ["./resources/videos/7.mp4",
"./resources/videos/1.mp4",
"./resources/videos/2.mp4",
"./resources/videos/3.mp4"
];
var videos = document.querySelector("#videos");
var result = document.querySelector("#result");
var template = "<li><label for='{0}'>Video {1}</label><input id='{0}' type='checkbox' onchange='onChange()'/></li>";
var selectedArray = [];
// Set up html
videos.innerHTML = originalVideoList.map(function(video) {
return template.replace(/\{0\}/g, video).replace(/\{1\}/g, video.split("/").pop());
}).join("");
// triggered on input change
function onChange() {
selectedArray = toArray(document.querySelectorAll("li>input:checked")).map(function(item) {
return item.id.replace("####.###", ".");
});
result.innerHTML = selectedArray.map(function(video) {
return "<li>" + video + "</li>";
}).join("");
}
// Same as [...input]
function toArray(input) {
var result = [];
for (var index = 0; index < input.length; index++) result[index] = input[index];
return result;
}
<ul id="videos"></ul>
<ul id="result"></ul>

Related

Check two arrays and its respective index as pair and find if a similar pair exist

I have a simple html code as below
<input type="text" id="key" name="key">
<input type="text" id="value" name="value">
<button id="check">Check</button>
and I have related jQuery code as well
var keyArray = [];
var valueArray = [];
$("#check").click(function() {
var keyVal = $("#key").val();
var valueVal = $("#value").val();
keyArray.push(keyVal);
valueArray.push(valueVal);
console.log(keyArray);
console.log(valueArray);
for ($i = 0; $i < keyVal.length; $i++) {
//Need to add some code here to check
}
});
What I want is, whenever if someone click the Check button, it has to check if there is a similar item added before into the respective index of keyArray and valueArray. Eg: First I add 1 into the id key and 2 into the id value. If I add 1 and 2 into key and value fields a second time, it should prompt me such a pair already added.
How can I achieve this with JavaScript or jQuery?
var keyArray = [];
var valueArray = [];
$("#check").click(function() {
var keyVal = $("#key").val();
var valueVal = $("#value").val();
var exist=false;
if(keyArray.length>0){
for (i = 0; i < keyArray.length; i++) {
if(keyArray[i]==keyVal && valueArray[i]==valueVal)
{
console.log("pair exist");
exist=true;
break;
}
}
}
if(!exist)
{
keyArray.push(keyVal);
valueArray.push(valueVal);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="key" name="key">
<input type="text" id="value" name="value">
<button id="check">Check</button>
If you want, you can introduce a third array and store data in it, and compare it with your value.
var keyArray = [];
var valueArray = [];
var newArray = [];
$("#check").click(function() {
var keyVal = $("#key").val();
var valueVal = $("#value").val();
var isExist = false;
for (i = 0; i < newArray.length; i++) {
if(newArray[i].key == keyVal && newArray[i].value == valueVal ){
isExist = true;
break;
}
else{
isExist = false;
}
}
if (isExist){
alert("such a pair already added");
}
else{
keyArray.push(keyVal);
valueArray.push(valueVal);
newArray.push({ key : keyVal, value : valueVal });
}
console.log(keyVal);
console.log(valueVal);
console.log(newArray);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="key" name="key">
<input type="text" id="value" name="value">
<button id="check">Check</button>

Javascript loop array for form validation

I have a table form with some rows, that are controlled by user. Meaning they can add as more as they want. Let's pretend user requested 5 rows and i need to check if they all have values.
function validateForm() {
var lastRowInserted = $("#packageAdd tr:last input").attr("name"); // gives me "packageItemName5"
var lastCharRow = lastRowInserted.substr(lastRowInserted.length - 1); // gives me 5
var i;
for (i = 1; i <= lastCharRow; i++) {
var nameValidate[] = document.forms["packageForm"]["packageItemName"].value;
if(nameValidate[i].length<1){
alert('Please fill: '+nameValidate[i]);
return false;
}
}
}
How can i receive packageItemName1 to 5 values in a loop so then I can use to validate them. Want the loop to process this code
var nameValidate[] = document.forms["packageForm"]["packageItemName1"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName2"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName3"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName4"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName5"].value;
Like this
const validatePackageItems = () => {
const nameValidate = $("form[name=packageForm] input[name^=packageItemName]"); // all fields with name starting with packageItemName
const vals = nameValidate.map(function() { return this.value }).get(); // all values
const filled = vals.filter(val => val.trim() !== ""); // all values not empty
console.log("Filled", filled, "= ", filled.length, "filled of", vals.length)
return filled.length === vals.length
};
$("[name=packageForm]").on("submit",(e) => {
if (!validatePackageItems()) {
alert("not valid");
e.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="packageForm">
<input type="text" name="packageItemName1" value="one" /><br/>
<input type="text" name="packageItemName2" value="two" /><br/>
<input type="text" name="packageItemName3" value="" /><br/>
<input type="text" name="packageItemName4" value="four" /><br/>
<input type="submit">
</form>
You can use string interpolation to get the key dynamically:
for (let i = 1; i < 6; i++) {
const currentValue = document.forms.packageForm[`packageItemName${i}`]
console.log('current value:', currentValue)
}

How to format jQuery .map() with keys and values?

I try to create array with keys and values by using the jQuery .map().
When I use my code I have a problem with formatting:
["name1:1", "name2:1", "name3:0"]
I need:
['name1':1,'name2':1,'name3':0]
I spend a few hours to make it work, but I don't know what is wrong.
HTML
<div class="inputs-container">
<input id="name1" name="name1" type="checkbox" class="multicheckbox-item" value="1" checked="checked">
<input id="name2" name="name2" type="checkbox" class="multicheckbox-item" value="1" checked="checked">
<input id="name3" name="name3" type="checkbox" class="multicheckbox-item" value="0">
</div>
JS
var inputsContainer = $('.inputs-container');
var inputValues = inputsContainer.find( 'input.multicheckbox-item' ).map( function() {
var name = $(this).attr('name');
var active = 0;
if( $(this).prop( 'checked' ) ){
var active = 1;
}
return name + ':' + active;
}).get();
console.log( inputValues );
You'll want an object and .each (or .forEach in native array terms).
var inputsContainer = $('.inputs-container');
var inputValues = {};
var inputValues = inputsContainer.find('input.multicheckbox-item').each( function() {
inputValues[$(this).attr('name')] = ($(this).prop('checked') ? 1 : 0);
});
console.log(inputValues);
Try This
var inputsContainer = $('.inputs-container');
var inputValues_key = inputsContainer.find( 'input.multicheckbox-item' ).map(function() {
var name = $(this).attr('name');
return name;
}).get();
var inputValues_value = inputsContainer.find( 'input.multicheckbox-item' ).map(function() {
var active = $(this).prop('checked')? 1 : 0;
return active;
}).get();
var inputValues = [], length = Math.min(inputValues_key.length, inputValues_value.length);
for(var i = 0; i < length; i++) {
inputValues.push([inputValues_key[i], inputValues_value[i]]);
}
console.log( inputValues );

Adding value of selected radio button to an equation

I am at my wits end. I cannot figure out how to add the value of the radio button to the equation. Can someone give me a clue at least on this??
If I don't have the radio button function included, this works fine.
<input type="radio" class="InternetCost" name="int" id="no_int" value="0">None<br>
<input type="radio" class="InternetCost" name="int" id="ten" value="10">10<br>
<input type="radio" class="InternetCost" name="int" id="twenty" value="20">20<br>
<input type="radio" class="InternetCost" name="int" id="thirty" value="30">30<br>
//Try to select radio button
var values = document.getElementsByName("int");
function getValue() {
for(var i = 0; i < values.length; i++) {
if(values[i].checked == true) {
selectedValue = values[i].value;
console.log('value=' + selectedValue);
}
}
}
function calculate()
{
//get selectedValue - this is where I am lost!
var radioValue = getValue()*1;
//Package
var pkgCost = document.getElementById("pkg").value*1;
//Package - Static
var equipPkg = document.getElementById("pep").value*1;
//Additional amount
var addBox = document.getElementById("addtl").value*1;
//Additional Box cost - static
var totalNum = document.getElementById("add_cost").value*1;
//Service amount
var dvrSvc = document.getElementById("dvr_svc").value*1;
//Service cost - static
var dvrCost = document.getElementById("dvr_cost").value*1;
// Sum everything
var SumAll = pkgCost + equipPkg + (addBox*totalNum) + (Svc*Cost) + radioValue;
// print the total
document.getElementById("Sum").innerHTML = SumAll.toFixed(2)
}
Your solution should work fine except you're using
console.log('value=' + selectedValue);
instead of actually returning the value.
return selectedValue;
Example

js get radio label text

i have this code :
<input type=radio name="vote_x" value="5">
<label for="vote_x">blabla</label><br>
how can i get the label value for radio with id of vote_x [using JS] ??
thanks
If you put an id on the label like this
<input type="radio" name="vote_x" value="5">
<label id="for_vote_x" for="vote_x">blabla</label>
You can then use
var textinlabel = document.getElementById("for_vote_x").innerHTML;
Edited: With out using an id for the label element
var labelElements = document.getElementsByTagName("label");
for (var i = 0, var labelElement; labelElements[i]; i++) {
if (labelElement.getAttribute("for") == "vote_x") {
//this is the labelElement you want
//code goes here
}
}
Ideally you would want to create a Generic function for this
function getlabelforinput(inputname) {
var labelElements = document.getElementsByTagName("label");
for (var i = 0, var labelElement; labelElements[i]; i++) {
if (labelElement.getAttribute("for") == inputname) {
return labelElement
}
}
return null;
}
Modern answer
Use document.querySelector('label[for="INPUT_ID"]') to get the label element corresponding to the input with given id.
Example:
const label = document.querySelector('label[for="vote_x"]');
console.log(label.textContent.trim());
<input type=radio name="vote_x" value="5">
<label for="vote_x">blabla</label>
You can try this
var el = document.getElementById("vote_x");
while(el.nextSibling && !(/label/i.test(el.nextSibling.tagName))){
el = el.nextSibling;
}
var text = el.nextSibling.innerHTML
You can check it in this fiddle.

Categories

Resources