Angular js bind local array with global scope - javascript

I have an angular form. only 2 input box. I am taking the
values from input box and then saving them in an array.
then the problem begins.
I want to show the array wrapped with <pre></pre> tag
how do I do that. Code sample is like this.
<input type="text" class="form-control" id="qus" placeholder="Enter Question" ng-model="qus">
<input type="text" class="form-control" id="op1" placeholder="Option 1" ng-model="op1">
<label><input type="checkbox" ng-model="correct1">Correct</label>
<button class="form-control btn btn-primary" ng-click = "save()">Save</button>
<pre ng-bind="dataShow"></pre>
Script:
var app = angular.module('qApp', []);
app.controller('qCtrl', function($scope) {
var set = [];
var op1 = [];
$scope.save = function (){
if($scope.correct1!==true){$scope.correct1=false;}
op1.push($scope.op1, $scope.correct1);
var qus = [$scope.qus, op1];
set.push(qus);
console.log(qus);
console.log(set);
return set;
};
$scope.dataShow = set.toString();
});

Move $scope.dataShow = set.toString(); inside the function and remove the return:
$scope.save = function () {
var set = [];
var op1 = [];
if ($scope.correct1 !== true) {
$scope.correct1 = false;
}
op1.push($scope.op1, $scope.correct1);
var qus = [$scope.qus, op1];
set.push(qus);
console.log(qus);
console.log(set);
$scope.dataShow = set.toString();
};

Related

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

Why I don't success to output simple js algorithem?

the user need to write the name of the animal, and I need to output the name+animalCode connected.
For some reason I am not getting any output.
Here is the code:
var str = "Cow12,Dog3,Cat721,Lion532";
var getInput = document.getElementById("inp1");
var getSubmit = document.getElementById("subm1");
getSubmit.onclick = function() {
var input = getInput;
var firstPlace = str.indexOf(input);
var numPlace = str.indexOf(",", firstPlace);
var newWord = str.slice(firstPlace, numPlace);
document.getElementById("print").innerHTML = newWord;
};
<form>
<input id="inp1" type="text">
<input id="subm1" type="submit">
</form>
<p id="print"></p>
Thank you very much for the help ! :)
You are just missing the .value part.
var str = "Cow12,Dog3,Cat721,Lion532";
var getInput = document.getElementById("inp1");
var getSubmit = document.getElementById("subm1");
getSubmit.onclick = function(event) {
event.preventDefault();
var input = getInput.value;
var firstPlace = str.indexOf(input);
var numPlace = str.indexOf(",", firstPlace);
var newWord = str.slice(firstPlace, numPlace);
document.getElementById("print").innerHTML = newWord;
};
<form>
<input id="inp1" type="text">
<input id="subm1" type="submit">
</form>
<p id="print"></p>
Make the following change :
Remove form tag as there is no need for that.
var str = "Cow12,Dog3,Cat721,Lion532";
function getSubmit()
{
var input = document.getElementById("inp1").value;
var firstPlace = str.indexOf("",input);
var numPlace = str.indexOf(",", firstPlace);
var newWord = str.slice(firstPlace, numPlace);
document.getElementById("print").innerHTML = newWord;
}
<input id="inp1" type="text">
<button id="subm1" onclick="getSubmit()">Submit</button>
<p id="print"></p>

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

JavaScript nested function not refreshing in dropdown

I have this JavaScript: http://jsfiddle.net/Lanti/4454ve0n/11/
The working code is commented out. I want to move out some lines and make them "global" under use strict creating nested functions, following this tutorial: http://www.w3schools.com/js/tryit.asp?filename=tryjs_function_counter3
I'm new to JavaScript.
Someone can explain why my solution is not working in the widthHeightUnit() function? It's not refreshing on click, just only if I press F5.
(function(){
////////////////////////// START OF: NESTED FUNCTIONS //////////////////////////
var widthHeightUnitVar = (function () {
var widthHeightUnitResult = document.getElementById('units').value;
return function () {return widthHeightUnitResult;}
})();
console.log(widthHeightUnitVar());
/////////////////////////// END OF: NESTED FUNCTIONS ///////////////////////////
window.onload = widthHeightUnit;
document.getElementById('units').addEventListener('click', widthHeightUnit);
function widthHeightUnit() {
//var widthHeightUnitResult = document.getElementById('units').value;
widthHeightUnitVar();
//document.querySelector('.width-unit').innerHTML = widthHeightUnitResult;
//document.querySelector('.height-unit').innerHTML = widthHeightUnitResult;
document.querySelector('.width-unit').innerHTML = widthHeightUnitVar();
document.querySelector('.height-unit').innerHTML = widthHeightUnitVar();
}
})();
(function() {
////////////////////////// START OF: NESTED FUNCTIONS //////////////////////////
var widthHeightUnitVar = (function() {
var widthHeightUnitResult = document.getElementById('units').value;
return function() {
return widthHeightUnitResult;
}
})();
console.log(widthHeightUnitVar());
/////////////////////////// END OF: NESTED FUNCTIONS ///////////////////////////
window.onload = widthHeightUnit;
document.getElementById('units').addEventListener('click', widthHeightUnit);
function widthHeightUnit() {
//var widthHeightUnitResult = document.getElementById('units').value;
widthHeightUnitVar();
//document.querySelector('.width-unit').innerHTML = widthHeightUnitResult;
//document.querySelector('.height-unit').innerHTML = widthHeightUnitResult;
document.querySelector('.width-unit').innerHTML = widthHeightUnitVar();
document.querySelector('.height-unit').innerHTML = widthHeightUnitVar();
}
document.getElementById('submit').addEventListener('click', dofCalc);
function dofCalc() {
var dofCalcWidth = document.getElementById('width').value;
if (dofCalcWidth.length === 0) {
alert('Please enter a real value to width!');
return;
}
var dofCalcHeight = document.getElementById('height').value;
if (dofCalcHeight.length === 0) {
alert('Please enter a real value to height!');
return;
}
var result = (+dofCalcWidth + +dofCalcHeight) / 2 // The + before the variables is "string to number conversion"
//document.getElementById('result').innerHTML = result + ' ' + document.getElementById('units').value;
document.getElementById('result').innerHTML = result + ' ' + widthHeightUnitVar();
}
})();
<form>
Select your width/height unit:
<br>
<select id="units">
<option value="feet">feet</option>
<option value="inches">inches</option>
<option value="meters">meters</option>
<option value="centimeters">centimeters</option>
<option value="milimeters" selected="selected">milimeters</option>
</select>
<br>
<br>Width:
<input type="number" id="width" /><span class="width-unit"></span>
<br>
<br>Height:
<input type="number" id="height" /><span class="height-unit"></span>
<br>
<br>
<input type="button" value="Submit" id="submit" />
<form/>
<br>
<br>Calculation:
<div id="result"></div>
Do it this way
var widthHeightUnitVar = function () {
var widthHeightUnitResult = document.getElementById('units').value;
return widthHeightUnitResult;
};
You were using IIFE so it was running immediately and only once, so it was not refreshing..
////////////////////////// START OF: NESTED FUNCTIONS //////////////////////////
var widthHeightUnitVar = (function () {
var widthHeightUnitResult = document.getElementById('units').value;
return function () {return widthHeightUnitResult;}
})();
console.log(widthHeightUnitVar());
/////////////////////////// END OF: NESTED FUNCTIONS ///////////////////////////

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