Javascript can't change input value - javascript

I'm trying to set a random number as value for an ons-input (signup_txtCodigo), but whenever I try to push the page it just shows me the alert that I put it to check the random and stays there.
This is the page template:
<!--External user register-->
<template id="signup.html">
<ons-page id="login-page" modifier="full_bg">
<ons-toolbar modifier="transparent">
<div class="center" style="font-size:150%;color:#f0f0f0">Estacionamiento UdeG</div>
<div class="left"><ons-back-button>Volver</ons-back-button></div>
</ons-toolbar>
<div align="center">
<br><img src="https://quimicabasicacucei.files.wordpress.com/2013/02/logo-udg.png?w=316" alt="logo" height=250px><br>
<p style="color:#f0f0f0">Registrar usuario</p>
<table>
<tr>
<td style="color:#f0f0f0">Código:</td>
<td><div contenteditable><ons-input input-id="signup_txtCodigo" type="text" modifier="underbar" readonly></ons-input></div></td> //this is the input I'm trying to change
</tr>
<tr>
<td style="color:#f0f0f0">Nombre:</td>
<td><ons-input input-id="signup_txtNombre" type="text" modifier="underbar" placeholder="Nombre"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Placa:</td>
<td><ons-input input-id="signup_txtPlaca" type="text" modifier="underbar" placeholder="Ej. A1B-2C3" maxlength="7"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Teléfono:</td>
<td><ons-input input-id="signup_txtTelefono" type="text" modifier="underbar" placeholder="Teléfono" maxlength="10"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Contraseña:</td>
<td><ons-input input-id="signup_txtPassword" type="password" modifier="underbar" placeholder="Contraseña" maxlength="10"></ons-input></td>
</tr>
</table><br>
<ons-button onclick="signup()" modifier="cta">Enviar</ons-button>
<ons-button onclick="cleanSignUp()" >Limpiar</ons-button><br><br>
</div>
</ons-page>
</template>
This is the function that should asign the value to the input and push the page:
//load signup page
function externalUserPage(){
var random = Math.floor((Math.random() * 999999999) + 111111111);
alert(random);
document.getElementById("signup_txtCodigo").value = random
document.querySelector('#myNavigator').pushPage('signup.html', {data: {title: 'signup'}});
}
thank you in advance

You are using The Content Template element and you have to remove the dot in the id.
so change
<template id="signup.html">
to
<template id="signuphtml">
you can access the content of the template like this
var content = document.querySelector('template#signuphtml').content;
to access you element use document.importNode
var clone = document.importNode(content, true);
var signup_txtCodigo = clone.querySelector("[input-id='signup_txtCodigo']");
now you can fill it using The textContent property
here an illustration
//load signup page
(function externalUserPage(){
var random = Math.floor((Math.random() * 999999999) + 111111111);
alert(random);
var content = document.querySelector('template#signuphtml').content;
var clone = document.importNode(content, true);
var signup_txtCodigo = clone.querySelector("[input-id='signup_txtCodigo']");
signup_txtCodigo.innerHTML = random;
//document.getElementById("signup_txtCodigo").value = random
console.log(signup_txtCodigo); document.querySelector('#myNavigator').pushPage('signup.html', {data: {title: 'signup'}});
})();
<!--External user register-->
<template id="signuphtml">
<ons-page id="login-page" modifier="full_bg">
<ons-toolbar modifier="transparent">
<div class="center" style="font-size:150%;color:#f0f0f0">Estacionamiento UdeG</div>
<div class="left"><ons-back-button>Volver</ons-back-button></div>
</ons-toolbar>
<div align="center">
<br><img src="https://quimicabasicacucei.files.wordpress.com/2013/02/logo-udg.png?w=316" alt="logo" height=250px><br>
<p style="color:#f0f0f0">Registrar usuario</p>
<table>
<tr>
<td style="color:#f0f0f0">Código:</td>
<td><div contenteditable><ons-input input-id="signup_txtCodigo" type="text" modifier="underbar" readonly></ons-input></div></td> //this is the input I'm trying to change
</tr>
<tr>
<td style="color:#f0f0f0">Nombre:</td>
<td><ons-input input-id="signup_txtNombre" type="text" modifier="underbar" placeholder="Nombre"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Placa:</td>
<td><ons-input input-id="signup_txtPlaca" type="text" modifier="underbar" placeholder="Ej. A1B-2C3" maxlength="7"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Teléfono:</td>
<td><ons-input input-id="signup_txtTelefono" type="text" modifier="underbar" placeholder="Teléfono" maxlength="10"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Contraseña:</td>
<td><ons-input input-id="signup_txtPassword" type="password" modifier="underbar" placeholder="Contraseña" maxlength="10"></ons-input></td>
</tr>
</table><br>
<ons-button onclick="signup()" modifier="cta">Enviar</ons-button>
<ons-button onclick="cleanSignUp()" >Limpiar</ons-button><br><br>
</div>
</ons-page>
</template>

you cannot change a field marked as readonly, you should use disabled
<ons-input input-id="signup_txtCodigo" type="text" modifier="underbar" disabled></ons-input>

In order to assign value to that input please check your function if it got call or you wrote it in document.ready.
for my idea this example should be work:
$( document ).ready(function() {
var random = Math.floor((Math.random() * 999999999) + 111111111);
document.getElementById("signup_txtCodigo").value = random;
});
Reference link : Input Text value Property

Just change input-id="signup_txtCodigo" to id="signup_txtCodigo"
I did a quick google search, but from what I can gather, input-id is not a valid OnSen element attribute, therefore you cannot select it by Id by conventional JavaScript means.

Related

Dynamically update cart totals using JS and HTML?

I'm making a simple cart page for a website and wanted to have cart totals update dynamically. For some reason nothing adjusts though. I also don't receive an error or any activity in the console which makes me wonder if I'm using class names improperly. It's been a long time since I've tried this so apologies for forgetting how haha. Here is my html:
<tr>
<td>
<div class="cart-info">
<img src="images/watercolor2.jpg">
<div>
<p>Watercolor Set</p>
<div class="price" data-amount="25.00">Price: $25.00</div><br>
Remove
</div>
</div>
</td>
<td><input class="quantity" type="number" value="0"></td>
<td class="total">$0.00</td>
</tr>
and js:
var quantity = document.getElementsByClassName("quantity");
Array.prototype.forEach.call(quantity, update);
function update(val, i){
val.addEventListener('input', function(){
var x = val.value;
document.getElementsByClassName('total')[i].innerHTML = "$" +
(x*document.getElementsByClassName('price')[i].getAttribute("data-amount")).toFixed(2);
});
};
I've double checked the script src is spelled properly and is posted above the tag in the html file...what am I overlooking? Is there a better approach?
This is how I'd approach it. Use querySelectorAll in concert with closest(), applying the function through an input event listener. Also, you can access the data-amount via the dataset property
const doGrandTotal = () => {
let gtotal = 0;
document.querySelectorAll('.total').forEach(t => {
gtotal += +t.innerText.replaceAll("$", "")
})
document.querySelector('#gtotal').innerText = `$${gtotal.toFixed(2)}`;
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.quantity').forEach(q => {
q.addEventListener('input', e => {
let p = +e.target.closest('tr').querySelector('[data-amount]').dataset.amount * +e.target.value;
e.target.closest('tr').querySelector('.total').innerText = `$${p.toFixed(2)}`;
doGrandTotal()
})
})
doGrandTotal()
})
<table>
<tr>
<td>
<div class="cart-info">
<img src="images/watercolor2.jpg">
<div>
<p>Watercolor Set</p>
<div class="price" data-amount="25.00">Price: $25.00</div><br>
Remove
</div>
</div>
</td>
<td><input class="quantity" type="number" value="0"></td>
<td class="total">$0.00</td>
</tr>
<tr>
<td>
<div class="cart-info">
<img src="images/watercolor2.jpg">
<div>
<p>Watercolor Set</p>
<div class="price" data-amount="25.00">Price: $25.00</div><br>
Remove
</div>
</div>
</td>
<td><input class="quantity" type="number" value="0"></td>
<td class="total">$0.00</td>
</tr>
</table>
<hr> Grand total: <span id='gtotal'></span>

JavaScript calc function - no longer works after switching to Bootstrap4

I am shifting a website over to Bootstrap4. One of the pages contained a simple calculator to generate percentages based on user input. This worked fine on the old site using basic HTML with no additional framework but no longer responds to the user input.
I tried double checking against a similar real-time calculator (http://javascript-coder.com/javascript-form/javascript-calculator-script.phtml), but I can't seem to get that one to work either.
function getSupport() {
var theForm = document.forms["calculator"];
var supportV = theForm.elements["support"];
var indvSupport = 0;
if (support.value != "") {
indvSupport = parseInt(supportV.value);
}
return indvSupport;
}
function getTotal() {
var indvSupport = getSupport();
//set values
var parentV = (indvSupport * 0.535).toFixed(2);
var partnersV = (indvSupport * 0.0760).toFixed(2);
var programsV = (indvSupport * 0.06).toFixed(2);
var staffV = (indvSupport * 0.255).toFixed(2);
var adminV = (indvSupport * 0.074).toFixed(2);
//display result
document.getElementById('parent').innerHTML = "$" + parentV;
document.getElementById('partners').innerHTML = "$" + partnersV;
document.getElementById('programs').innerHTML = "$" + programsV;
document.getElementById('staff').innerHTML = "$" + staffV;
document.getElementById('admin').innerHTML = "$" + adminV;
}
<form action="" id="calculator" onsubmit="return false;">
<table align="center" style="border:none;">
<tbody>
<tr>
<td style="font-weight: bold;">Total anticipated support:</td>
<td>$ <input id="support" name="support" oninput="getTotal()" type="text" /></td>
</tr>
<tr>
<td>Parent Organization (53.5%)</td>
<td>
<div id="parent" style="float: right;"> </div>
</td>
</tr>
<tr>
<td>Supporting Partners (7.6%)</td>
<td>
<div id="partners" style="float: right;"> </div>
</td>
</tr>
<tr>
<td>Programs & Support (6.0%)</td>
<td>
<div id="programs" style="float: right;"> </div>
</td>
</tr>
<tr>
<td>Staffing (25.5%)</td>
<td>
<div id="staff" style="float: right;"> </div>
</td>
</tr>
<tr>
<td>Administration (7.4%)</td>
<td>
<div id="admin" style="float:right;"> </div>
</td>
</tr>
</tbody>
</table>
</form>
Or at https://jsfiddle.net/zimerhonzl/ub7z09oL/9/
This is a fairly basic form where the user inputs their donation and can see how it will be distributed. Upon entry in the main box the lower fields should auto populate.
The "no wrap" solution in jsfiddle fixed the issue. On the actual site it turns out there was a code error above the snippet in the common.js file preventing the functions from loading properly. Unfortunately the CMS strips out any in-line javascript so I could not post the directly code above it on the actual page. Now the common.js file is properly loading the function prior to the form.

Unable to extract value using jQuery

I have a function to calculate when there is a change in one of the 3 input boxes and then display that answer. I'm able to trigger the function when there's a change but I'm unable to get the values from each of the inputs. Below are html and js snippets.
HTML:
<div>
<table>
<tr>
<th></th>
<th>Base</th>
<th class="gen-specific g3 g4 g5 g6">IVs</th>
<th class="gen-specific g3 g4 g5 g6">EVs</th>
<th></th>
<th></th>
</tr>
<tr class="hp" onchange="hp_calculator()">
<td>
<label>HP</label>
</td>
<td>
<input class="base" value="100" />
</td>
<td class="gen-specific g3 g4 g5 g6">
<input class="ivs calc-trigger" value="31" />
</td>
<td class="gen-specific g3 g4 g5 g6">
<input class="evs calc-trigger" type="number" min="0" max="252" step="4" value="0" />
</td>
<td><span class="total">341</span>
</td>
<td></td>
</tr>
</table>
</div>
JS:
function hp_calculator() {
var hp = $(this).find(".base").val()*$(this).find(".iv calc-trigger").val()+$(this).find(".ev calc-trigger").val();
$(this).find(".total").val(hp);
}
Firstly this is going to be the window and not the element. Pass the element inside your handler instead and use the parameter.
<tr class="hp" onchange="hp_calculator(this)">
Then you need to change your class selectors.class1.class2 for a many class selector, and then .text() to change the text of the span element. A final note is you left off the "s" in both ivs and evs:
function hp_calculator(ele) {
var hp = $(ele).find(".base").val()*$(ele).find(".ivs.calc-trigger").val()+$(ele).find(".evs.calc-trigger").val();
$(ele).find(".total").text(hp);
}
Demo
Note
It's generally bad practice to give event handlers inline. Rather I would recommend you to attach them directly in JavaScript, this way this will work as you would expect. Here is an example how you would do so in jQuery (demo):
$('.hp').change(function(){
var hp = $(this).find(".base").val()*$(this).find(".ivs.calc-trigger").val()+$(this).find(".evs.calc-trigger").val();
$(this).find(".total").text(hp);
});

I'm trying to create an html form to generate an url address based on input to a field

I am trying to create a small HTML document for my team to use to create fake devices for testing purposes in our program. We currently have a link to do this with but we have to manually change parts of it in the URL field before hitting enter to process it. I came up with the idea of creating this form so we can make sure that we are filling in all the elements of the URL correctly and then copy and paste the created URL into the browser. There are static parts of the address that we don't change and then there are values we update after the '=' sign. There are 4 different environments that we can use this in.
I admit it has been a while since I last worked in HTML so I've been trying to search forums and sites like W3School to find the segments of code that I think will serve the purpose I'm aiming for. The following code is where I have gotten so far but can't get it to work the way I've intended it to. If anyone can provide suggestions or feedback on what I missed or did wrong I'd appreciate it. Thank you!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Item birth generator</title>
<script>
function mySubmit() {
var addStart;
var addPart1 = "part1=";
var addPart2 = "&part2=";
var addPart3 = "&part3=";
var addPart4 = "&part4=";
var addPart5 = "&part5=";
var addPart6 = "&part6=";
var addPart7 = "&part7=";
var addPart8 = "&part8=";
var myChoice = "choice";
if (myChoice.value == "choice1")
{addStart="https://address1?";}
else if (myChoice.value == "choice2")
{addStart="https://address2?";}
else if (myChoice.value == "choice3")
{addStart="https://address3?";}
else (myChoice.value == "choice4")
{addStart="https://address4?";}
var address = addStart.concat(addPart1, "mInput1", addPart2, "mInput2", addPart3, "mInput3", addPart4, "mInput4", addPart5, "mInput5", addPart6, "mInput6", addPart7, "mInput7", addPart8, "mInput8");
document.getElementById("demo").innerHTML = address;
}
</script>
</head>
<body>
<font> <H3>Please fill in the appropriate fields and then click Generate to create a url for an item in the chosen environment.</H3></font>
<form target="_self" id="demo" name="item" method="post" onSubmit="return checkValue();">
<input type="radio" name="choice" id="ch1" value="choice1" checked> Choice 1 <input type="radio" name ="choice" id="ch2" value="choice2"> Choice 2 <input type="radio" name="choice" id="ch3" value="choice3"> Choice 3 <input type="radio" name ="choice" id="ch4" value="choice4"> Choice 4
<br><br>
<table>
<tbody>
<tr>
<td>Item Part 1</td>
<td><input type="text" name="mInput1" maxlength="13"></td>
</tr>
<tr>
<td>Item Part 2</td>
<td><input type="text" name="mInput2"></td>
</tr>
<tr>
<td>Item Part 3</td>
<td><input type="text" name="mInput3"></td>
</tr>
<tr>
<td>Item Part 4</td>
<td><input type="text" name="mInput4"></td>
<tr>
<td>Item Part 5</td>
<td><input type="text" name="mInput5"></td>
</tr>
<tr>
<td>Item Part 6</td>
<td><input type="text" name="mInput6"></td>
</tr>
<tr>
<td>Item Part 7</td>
<td><input type="text" name="mInput7"></td>
</tr>
<tr>
<td>Item Part 8</td>
<td><input type="text" name="mInput8"></td>
</tr>
<tr>
</tr>
<tr>
<td><input type="submit" value="Generate" onclick="mySubmit()"></td>
</tr>
</tbody>
</table>
<br>
<input type="text" size="250" name="address" value=''>
</form>
</body>
</html>
There is an error with this line:
var s.address = s.addStart.concat(addPart1, mInput1, addPart2, mInput2, addPart3, mInput3, addPart4, mInput4, addPart5, mInput5, addPart6, mInput6, addPart7, mInput7, addPart8, mInput8);
Verify what you are using is valid by testing the variables (output with a console.log or an alert) and check the command syntax. :)

Model is not getting updated - AngularJS

I have a simple page where there are list of existing item (these can be modified) and option to add new items to the existing list.
There are 2 sections, CodeLookup and Benchmark. Design of both section is same ( as explained above).
There is a link which will restore all the changes back to the initial state of page.
On JS , there are arrays, one for storing the list which is displayed and a backup array which stores initial state of list. There is an add function which adds newly input data to the list. Lastly there is a cancel method (linked to cancel link) which will restore the list to its initial state. This cancel method just put the original list in the list used to display data.
Now the codelookup value is restored on hit of cancel the first time. But if you modify again in the list and hot cancel, restoration doesnot happen. Also benchmark is not resored at all. I have put breakpoint on Chrome dev tool and found that the list contain the values from original list however its not reflecting on UI.
Any help in fixing this is appreciated.
Below is the code :
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<SCRIPT type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></SCRIPT>
<script type="text/javascript">
var referenceDataMaintainenceApp = angular.module('referenceDataMaintainenceApp',[] );
referenceDataMaintainenceApp.controller('referenceDataMaintainenceCtrl', function ($scope) {
$scope.orig_lookup_codes_details;
$scope.orig_calendar_details;
$scope.orig_pams_fields;
$scope.orig_brokers_details;
$scope.lookup_codes_details = [{'lookupName':'ac_asset','codeName':'ABCD','codeDetail':'sdfsdfsdf','ruleDetail':'sdsdsdsdsd','active':false}];
$scope.benchmarks_details = [{'benchmarkName':'Bench1','benchmarkDesc':'First Entry','active':false}];
$scope.orig_lookup_codes_details = angular.copy($scope.lookup_codes_details);
$scope.orig_brokers_details = angular.copy($scope.benchmarks_details);
$scope.addLookupCode = function() {
$scope.lookup_codes_details.push($scope.new_lookup_code);
$scope.new_lookup_code = getLookupCodeObject();
};
$scope.addBenchMark = function() {
$scope.benchmarks_details.push($scope.new_benchmark);
$scope.new_benchmark = getBenchMarkObject();
};
$scope.cancelData = function() {
$scope.brokers_details = $scope.orig_brokers_details;
$scope.lookup_codes_details = $scope.orig_lookup_codes_details;
console.log("sdsd");
//$http.post('/data/save', $scope.benchmarks_details);
};
});
function getLookupCodeObject () {
lookup_code = {
lookupName : '',
codeName : '',
codeDetail : '',
ruleDetail : '',
active : false
};
return lookup_code;
}
function getBenchMarkObject () {
benchmark = {
benchmarkName : '',
benchmarkDesc : '',
benchmarkId : '',
benchmarkType : ''
};
return benchmark;
}
</script>
</head>
<body ng-app="referenceDataMaintainenceApp" ng-controller="referenceDataMaintainenceCtrl" >
<div><A class="operationalnav" ng-click="cancelData()"
href="javascript:;">Cancel</A> </div>
<br />
<br />
<TABLE id="tblGridLookupCodes" class="tableData" border="0"
width="100%">
<THEAD>
<TR bgColor="#eaeaea">
<TD class="tableTitle" noWrap>Code Name</TD>
<TD class="tableTitle" noWrap>Description</TD>
<TD class="tableTitle" noWrap align="center">Active</TD>
</TR>
</THEAD>
<TBODY>
<TR ng-repeat="lookup_code_detail in lookup_codes_details">
<td nowrap="nowrap">{{lookup_code_detail.codeName}}</td>
<td nowrap="nowrap">
<input type="text" name="codeLookupBean[0].codeDescription"
maxlength="100" size="80" ng-model="lookup_code_detail.codeDetail" />
</td>
<td nowrap="nowrap" align="center">
<input type="checkbox" name="codeLookupBean[0].active"
ng-model="lookup_code_detail.active" />
</td>
</TR>
</TBODY>
</TABLE>
<HR width="100%">
<table>
<tr>
<td>
<INPUT id="codeNameInput" name="codeNameInput"
maxLength="32" ng-model="new_lookup_code.codeName" />
</td>
<td>
<INPUT id="descInput" name="descInput" maxLength="100"
size="80" ng-model="new_lookup_code.codeDetail">
</td>
<td>
<INPUT id="activeInput" name="activeInput" CHECKED type="checkbox"
ng-model="new_lookup_code.active" />
</td>
<td>
<INPUT id="btnAddRow" class="btnz" title="Add Row"
ng-click="addLookupCode($event)" name="btnAddRow" value=" Add "
type="button" />
</td>
</tr>
</table>
<br /><br /><br />
<TABLE id="tblGridBenchmarks" class="tableData" border="0" width="100%">
<THEAD>
<TR bgColor="#eaeaea">
<TD class="tableTitle" noWrap>Benchmark Name</TD>
<TD class="tableTitle" noWrap>Description</TD>
</TR>
</THEAD>
<TBODY>
<TR ng-repeat="benchmark_detail in benchmarks_details">
<TD>{{benchmark_detail.benchmarkName}}</TD>
<TD><INPUT name="benchmarkBean[0].benchmarkDesc"
maxLength="255" size="120" ng-model="benchmark_detail.benchmarkDesc"></TD>
</TR>
</TBODY>
</TABLE>
<HR width="100%">
<table>
<tr>
<td>Enter Benchmark Name:<BR> <INPUT
id="benchmarkNameInput" name="benchmarkNameInput"
ng-model="new_benchmark.benchmarkName" maxLength="100" size="30">
</td>
<td>Description:<BR> <INPUT name="benchmarkDescInput"
ng-model="new_benchmark.benchmarkDesc" maxLength="255" size="80">
</td>
<td><INPUT id="btnAddRowComment" class="btnz" title="Add Row"
ng-click="addBenchMark($event)" name="btnAddRowComment"
value=" Add " type="button"></td>
</tr>
</table>
It seems like $digest cycle was not run at all or correctly.
try to run $scope.$apply() and see if it works.
example:
http://jsfiddle.net/00d0ux1x/
For more information see
http://www.sitepoint.com/understanding-angulars-apply-digest/
However in your case problem is
javascript:; change to javascript:void(0);
use angular.copy(); to copy original array if you don't want to modify it in later use.
in cancel function you are setting $scope.brokers_details and in view using $scope.benchmarks_details. (also having orig_brokers_details)
See fixed solution
http://jsfiddle.net/00d0ux1x/3/

Categories