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

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 );

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)
}

Create an array of selected radio button values

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>

How to retrieve session storage values and pass it to radio buttons and checkboxes?

As the question is asking, can you get the values from the session storage or local storage to radio buttons on html and the same thing for the checkboxes?
My code:
var customername = {"firstname" : getCookie("firstname"), "lastname" : getCookie("lastname")};
var curcustomer1 = {"firstname" : getCookie("firstname"), "lastname" : getCookie("lastname")};
var lastvist = {"date" : dateall} // only display the date and time
var myJSON = JSON.stringify(customername);
var myJSON1 = JSON.stringify(lastvist); // has the date when the user last has visited
var myJSON2 = JSON.stringify(curcustomer1);
var myJSON3full = JSON.stringify(custinfo);
sessionStorage.setItem("custinfo", myJSON3full);
var objectfull = sessionStorage.getItem("custinfo");
objfull = JSON.parse(objectfull);
var object = sessionStorage.getItem("customername");
obj = JSON.parse(object);
if(object != myJSON) {
sessionStorage.setItem("customername", myJSON);
var object = sessionStorage.getItem("customername");
obj = JSON.parse(object);
var curcustomer = customername;
var myJSONcopy = JSON.stringify(curcustomer);
var object2 = sessionStorage.setItem("curcustomer", myJSONcopy);
var msg5 = "Welcome ";
document.getElementById("customer").innerHTML = msg5 + " " + "New Customer";
document.getElementById("date1").innerHTML = "";
var radiobtn = document.getElementsByName("type");
if(radiobtn.value != 8) {
document.elem.type.value="8";
}
var radiobtn1 = document.getElementsByName("special");
if(radiobtn1.value != 0) {
document.elem.special.value="0";
}
for (var i = 0; i < extras.length; i++) {
if (extras[i].checked) {
extras[i].checked = false;
}
}
}
if(object == myJSONcopy) {
radiobtn = document.getElementsByClassName("type").innerHTML = sessionStorage.getItem("type");
radiobtn1 = document.getElementsByClassName("special").innerHTML = sessionStorage.getItem("special");
checboxes = document.getElementsByClassName("extras").innerHTML = sessionStorage.getItem("extras");
}
<td>
<input type="radio" name="type" value="8" checked>Small $8.00
<br>
<input type="radio" name="type" value="10">Medium $10.00
<br>
<input type="radio" name="type" value="15">Large $15.00
<br>
<input type="radio" name="type" value="18">Extra Large $18.00
<br>
<br>
</td>
if you are trying to add the item to multiple buttons that share the same className then you will have to do something like this:
var list = document.getElementsByClassName('type');
var i;
for (i = 0; n < list.length; ++i) {
list[i].value= sessionStorage.getItem('events')
};
But if it's just one button then I will suggest you use getElementById
like this
document.getElementById('Id').value = sessionStorage("events");

java script functions for different textbox my code here

This is my code in html and java script. I coded same things thrice, I want to do it once... what to do...............
<input type="text" name="option1" id="option1" onblur="calc_amt(1);">
<input type="text" name="price1" id="price1" onblur="calc_amt(1);">
<input type="text" name="amount1" id="amount1" readonly>
<input type="text" name="option2" id="option2" onblur="calc_amt(2);">
<input type="text" name="price2" id="price2" onblur="calc_amt(2);">
<input type="text" name="amount2" id="amount2" readonly>
<input type="text" name="option3" id="option3" onblur="calc_amt(3);">
<input type="text" name="price3" id="price3" onblur="calc_amt(3);">
<input type="text" name="amount3" id="amount3" readonly>
<script>
function calc_amt(val){
if(val==1){
var option1 = document.getElementById("option1").value;
var pri1 = document.getElementById("price1").value;
....
document.getElementById("amount1").value=amoun1 ;
}
if(val==2){
var option2 = document.getElementById("option2").value;
var pri2 = document.getElementById("price2").value;
...
document.getElementById("amount2").value=amoun2;
}
if(val==3){
var option3 = document.getElementById("option3").value;
var pri3 = document.getElementById("price3").value;
....
document.getElementById("amount3").value=amoun3;
}
var amoun1=document.getElementById("amount1").value;
var amoun2=document.getElementById("amount2").value;
var amoun3=document.getElementById("amount3").value;
var tot = Number(amt1)+Number(amt2)+Number(amt3);
document.getElementById("amount").value=tot;
}
</script>
how do solve it by coding only once... I am beginner please help me.... any other ideas to solve this.. i need a solution like inheritance.
You can further reduce above script like this. Your amoun is unclear for though. However you can reduce the code like this. This is just an idea and make sure you match the variables with correct statement.
<script>
function calc_amt(val){
var option1 = document.getElementById("option"+val).value;
var pri1 = document.getElementById("price"+val).value;
....
document.getElementById("amount"+val).value=""+amount+val ;
var amoun1=document.getElementById("amount1").value;
var amoun2=document.getElementById("amount2").value;
var amoun3=document.getElementById("amount3").value;
var tot = Number(amt1)+Number(amt2)+Number(amt3);
document.getElementById("amount").value=tot;
}
</script>
Replace:
if(val==1){
var option1 = document.getElementById("option1").value;
var pri1 = document.getElementById("price1").value;
document.getElementById("amount1").value=amoun1 ;
}
with:
var amoun = document.getElementById("amount" + val).value;
var option = document.getElementById("option" + val).value;
var pri = document.getElementById("price" + val).value;
document.getElementById("amount" + val).value=amoun;
TRY...
Remove all inline handler and use blur handler like in demo
$("input[type=text]").on("blur", function () {
var id = this.id;
var last = id.charAt(id.length - 1); // get last id string value
var optionValue = $("#option" + last).val();
var priceValue = $("#price" + last).val();
var option = isNaN(optionValue) ? 0 : +optionValue; // check is nan
var price = isNaN(priceValue) ? 0 : +priceValue;
$("#amount" + last).val(option * price); // display multiply value
$("#amount").text($("input[type=text][id^=amount]").map(function () { // collect all amount1,2,3 values
var value = $(this).val();
return isNaN(value) ? 0 : +value;
}).get().reduce(function (a, b) { // add total value
return a + b;
}));
});
DEMO
OPTIMIZED CODE
$("input[type=text]:not([readonly])").on("blur", function () {
var obj = $();
obj = obj.add($(this)).add($(this).prevUntil('[readonly]')).add($(this).nextUntil('[readonly]'));
$(this).nextAll('[readonly]').first().val($.map(obj, function (val, i) {
return parseInt(val.value, 10) || 0;
}).reduce(function (a, b) {
return a * b
}, 1));
$("#amount").text($("input[type=text][id^=amount]").map(function () {
var value = $(this).val();
return isNaN(value) ? 0 : +value;
}).get().reduce(function (a, b) {
return a + b;
}));
});
DEMO

Categories

Resources