I have upload my JavaScript code :
$(document).ready(function(){
$("#remain_credit").click("calculate_remain_credit");
});
function calculate_remain_credit() {
var hour_start = document.getElementById(parseInt('credit_taken'));
var hour_end = document.getElementById(parseInt('course_credit'));
var hour_total = credit_taken - course_credit;
document.getElementById('remain_credit').innerHTML = remain_credit;
}
And I am uploading also my Laravel form here:
<div class="form-group">
{{Form::label('credit',' Remain Credit ')}}
{!! Form::number('remain_credit', null, array('id'=>'remain_credit','placeholder' => ' Remain Credit ','class' => 'form-control')) !!}
</div>
How can I fix this problem?
You should fix three problems in your code :
The click event attachment should look like :
$("#remain_credit").click(calculate_remain_credit);
Removing the quotes :
$("#remain_credit").click("calculate_remain_credit");
__________________________^_______________________^
You need to replace innerHTML by value if you want to update the input value, should be :
document.getElementById('remain_credit').value = remain_credit;
You've to parse after getting the value so :
var hour_start = document.getElementById(parseInt('credit_taken'));
var hour_end = document.getElementById(parseInt('course_credit'));
Should be instead like :
var hour_start = parseInt( document.getElementById('credit_taken').value );
var hour_end = parseInt( document.getElementById('course_credit').value );
The full updated code will be :
$(document).ready(function(){
$("#remain_credit").click(calculate_remain_credit);
});
function calculate_remain_credit() {
var hour_start = parseInt( document.getElementById('credit_taken').value );
var hour_end = parseInt( document.getElementById('course_credit').value );
var hour_total = credit_taken - course_credit;
document.getElementById('remain_credit').value = remain_credit;
}
parseInt should be first and then document.getElementById:
$("#remain_credit").click(calculate_remain_credit);
function calculate_remain_credit() {
// here use parseInt before getElementById
var hour_start = parseInt(document.getElementById('credit_taken').value);
var hour_end = parseInt(document.getElementById('course_credit').value);
var hour_total = credit_taken - course_credit;
document.getElementById('remain_credit').value = hour_total;
}
Related
I'm looking for a js or jq way to remove # character while user is typing on a field.
I tried this:
$( function() {
$( ".remove-sharp" ).on( "keyup", function( event ) {
console.log( 'test' );
$( this ).val().replace( /\#/, "" );
} )
} );
I can see the "test" being printed in console but this has no effect on the characters in the field; it doesn't remove #. How to achieve this ?
The issue is because you're not setting the value of the input, only getting it and making the replacement and doing nothing with the resulting string. Try this:
$(function() {
$(".remove-sharp").on("keyup", function(event) {
var value = $(this).val();
if (value.indexOf('#') != -1) {
$(this).val(value.replace(/\#/g, ""));
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="remove-sharp" />
function validateCustomerName(){
var validatedName = "";
var restrictedCharactersArray = ["0","1","2","3","4","5","6","7","8","9","~","`","!","#","#","$","%","^","&","*","(",")","-","_",
"+","=","{","}","[","]",":",";","'","<",">",",",".","?","/","/\/","|"];
var customerName = document.getElementById("customerName").value;
var numberValidation = (/^[a-zA-Z_ ]+$/g).test(customerName);
if(!numberValidation){
validatedName = "";
var customerNameArray = customerName.split("");
for(var i=0;i<restrictedCharactersArray.length;i++){
var restrictedCharacter = restrictedCharactersArray[i];
if(customerNameArray.indexOf(restrictedCharacter) !== -1){
for(var j=0; j<customerNameArray.length; j++){
var customerNameCharacter = customerNameArray[j];
if(customerNameCharacter !== restrictedCharacter){
validatedName = validatedName+customerNameCharacter;
}
}
}
}
document.getElementById("customerName").value = validatedName;
}
}
<input type="text" id="customerName" onKeyUp="validateCustomerName();" />
I have this array in javascript:
[div.parts, div.editor, div.inside-1, div.container-2, div.inside-wrapper, div#content, div.whitebgpan, div, div#maindiv, body, html]
How can I convert it into string, so that the output will be:
div.parts div.editor div.inside-1 div.container-2 div.inside-wrapper div#content div.whitebgpan div div#maindiv body html
here is my code:
jQuery(document).on('click', function(e){
var ClickedParents = jQuery(e.target).parents(); //Get all parents of clicked element
var ClickedParents_array = jQuery.makeArray(ClickedParents); //Make array
console.log(ClickedParents_array); //Show output in colsole
});
You can use a combination of the jQuery each function and JavaScript's Array.Join function to solve this problem.
DEMO: http://jsfiddle.net/zay015ex/1/
I've artificially retrieved an array of jQuery objects to show how you can solve this, but the concept is common to your problem.
HTML
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="child4"></div>
<div id="child5"></div>
</div>
JavaScript
var arrayOfObjects = $('#parent').children();
var ids = [];
$.each(arrayOfObjects, function(i, val)
{
ids.push(val.id);
});
var idString = ids.join(' ');
You can read up more on the jQuery each function here.
You can read up more on the JavaScript's Array.Join function
here.
===== Update =====
Ok, the following code is tested, just open a console and paste this. it selects all div tags and convert into selector string.
$.map($('div'),function toSelector(elem){
var jqObj = $(elem)
var tag = jqObj.prop('tagName').toLowerCase()
var classes = jqObj.attr('class') ? '.' + jqObj.attr('class').split(' ').join('.') : ''
var ids = jqObj.attr('id') ? '#' + jqObj.attr('id').split(' ').join('#'): ''
return tag + classes + ids
})
===================
Supposing they're jquery objects, you have to build the string manually.
For example, do something like following. (not tested)
function toSelector(jqObj){
var tag = jqObj.prop('tagName').toLowerCase()
var classes = jqObj.attr('class') ? '.' + jqObj.attr('class').split(' ').join('.') : ''
var ids = jqObj.attr('id') ? '#' + jqObj.attr('id').split(' ').join('#'): ''
return tag + classes + ids
}
array.map(toSelector)
I think below code is helpful for you.
<script type="text/javascript">
String.prototype.replaceAll = function ( token, newToken, ignoreCase ) {
var _token;
var str = this + "";
var i = -1;
if ( typeof token === "string" ) {
if ( ignoreCase ) {
_token = token.toLowerCase();
while( (
i = str.toLowerCase().indexOf(
token, i >= 0 ? i + newToken.length : 0
) ) !== -1
) {
str = str.substring( 0, i ) +
newToken +
str.substring( i + token.length );
}
} else {
return this.split( token ).join( newToken );
}
}
return str;
};
try{
var arr = [];
arr.push('div.parts', 'div.editor', 'div.inside-1', 'div.container-2', 'div.inside-wrapper', 'div#content', 'div.whitebgpan', 'div', 'div#maindiv', 'body', 'html');
var stringData = arr.toString();
stringData = stringData.replaceAll(",", " ");
console.log(stringData);
}catch(e){
alert(e)
}
</script>
The functions below work fine, the only thing I need help with is that when I pick an option from a drop down menu, it runs the function, but it erases all of the options in the drop down box. How can I get it NOT to do that and continue displaying my original options in the same drop down box?
<script type="text/javascript">
function gbid(s) {
return document.getElementById(s);
}
function myCount() {
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("somefilepathhere.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var agent,count
agent=document.getElementById("tAgent").value;
if (agent=="Agent1")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(1,1).Value;
}
else if (agent=="Agent2")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(2,1).Value;
}
document.getElementById("disphere").innerHTML = count;
excel.Quit();
excel.Application.Quit();
}
function saveToExcel() {
var myApp = new ActiveXObject("Excel.Application");
myApp.visible = false;
var xlCellTypeLastCell = 11;
var x = document.forms["f1"]["tAgent"].value;
if (x == null || x == "") {
alert("You must select an 'Entered By' option!");
return false;
}
else
var myWorkbook = myApp.Workbooks.Open(filePath);
var myWorksheet = myWorkbook.Worksheets(1);
myWorksheet.Activate;
objRange = myWorksheet.UsedRange;
objRange.SpecialCells(xlCellTypeLastCell).Activate;
newRow = myApp.ActiveCell.Row + 1;
alert('A new log was created on row '+newRow);
strNewCell = "A" + newRow;
myApp.Range(strNewCell).Activate;
myWorksheet.Cells(newRow,1).value = f1.tMemberid.value;
myWorksheet.Cells(newRow,2).value = f1.tDate.value;
myWorksheet.Cells(newRow,3).value = f1.tRep.value;
myWorksheet.Cells(newRow,4).value = f1.tIssuerep.value;
myWorksheet.Cells(newRow,5).value = f1.tLOB.value;
myWorksheet.Cells(newRow,6).value = f1.tContactnum.value;
myWorksheet.Cells(newRow,7).value = f1.tMembername.value;
myWorksheet.Cells(newRow,8).value = f1.tIssid.value;
myWorksheet.Cells(newRow,9).value = f1.tTypeofissue.value;
myWorksheet.Cells(newRow,10).value = f1.tDiscofissue.value;
myWorksheet.Cells(newRow,11).value = f1.tTimesent.value;
myWorksheet.Cells(newRow,12).value = f1.tSendto.value;
myWorksheet.Cells(newRow,13).value = f1.tAgent.value;
myWorkbook.Close(true);
myApp.Workbooks.Close;
myApp.Close;
alert('Process Complete!');
}
</script>
<table >
<tr>
<td class="tb_bor" Align="center" ><h1>ACA Issues Tracker</h1><br />
<b>Entered By: </b>
<select name="tAgent" id="tAgent" style="80% !important;" onchange="myCount()">
<option value="" ></option>
<option value="Agent1" >Agent 1</option>
<option value="Agent2" >Agent 2</option>
</select>
<br />You have completed: <p id="disphere"></p>
<hr>
</td>
</tr>
</table>
With the below line you overwrite the inner text of your select field:
count = gbid( 'tAgent' ).innerText = excel_sheet.Cells( 1,1 ).Value;
^
|
Allthough I'm not clear on what you desire to achieve with the code because I don't understand your usecase, I think you might have mistaken the second equals sign with a string concatenation or something?
This might be what you tried to achieve:
count = gbid( 'tAgent' ).innerText + ' ' + excel_sheet.Cells( 1,1 ).Value;
This is a corrected version of your function:
function myCount() {
var excel = new ActiveXObject( 'Excel.Application' ),
excel_file = excel.Workbooks.Open( 'somefilepathhere.xlsx' ),
excel_sheet = excel.Worksheets( 'Sheet1' ),
agent = document.getElementById( 'tAgent' ).value,
count;
if ( agent === 'Agent1' ) {
count = excel_sheet.Cells( 1,1 ).Value;
} else if ( agent === 'Agent2' ) {
count = excel_sheet.Cells( 2,1 ).Value;
}
document.getElementById( 'disphere' ).innerHTML = count;
excel.Quit();
excel.Application.Quit();
}
I have a problem that i've been trying to solve for days.
I was wondering if it was possible to let a text turn into an integer.
So everytime i write in my textarea("ALC") Load, then on the textarea("MLC") 001. And also including 1-15 to binary at the end
E.g. Load #1 will show 001 0 00001
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC()";" /></p>
</form>
<script type= "text/javascript">
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = parseInt(x);
var bin = x.toString(2);
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
I think I understand what you want to do. You want to use what you type into "ALC" as a key to a value. In that case, you want to use a javascript object and assign the instructions as keys, and the binary to the value. Such as
var instruction_set = {
"Load" : "001",
"Store" : "010",
"Add" : "011",
"Sub" : "100",
"Equal" : "101",
"Jump" : "110",
"Halt" : "111"
}
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = instruction_set[x];
}
Updated:
Try this:
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC();" /></p>
</form>
<script type= "text/javascript">
var Dict = { 'Load':"001",'Store':"010"}; //example Instruction set
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
var instrType = '';
for (var instr in Dict){
var ind = x.indexOf(instr);
if( ind > -1){
instrType = instrType + Dict[instr];
x = x.replace(instr,'');
}
}
console.log(instrType, "::", x);
x = parseInt(x);
var bin = x.toString(2);
bin = instrType + bin;
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
Lets say you have a way to get the tokens. Then your function should look like this
var tokens = getTokens( document.getElementById("ALC").value ) ;
var vocabulary = { "Load" : "001" , " ... " } ;
var output = []
var i = 0;
var tokensLength = tokens.length;
for ( ; i < tokensLength; i++){
var token = tokens[i];
if ( isNaN(token) && typeof(vocabulary[token]) != "undefined" ){
output.push( vocabulary[token] );
}else if ( !isNaN(token) ){
output.push( Number(token).toString(2) );
}else{
console.log(["error : unknown token ", token]);
}
}
document.getElementById("MLC").value = output.join(" ");
I see in the question that Load translates to 0010 and not 001, so I would simply modify the vocabulary.
Explanation :
I assume you have a way to split the input to tokens. (the ALC syntax is still unclear to me).
The tokens array will contains, for example ["Load","#","15", "Load","#","16"] and so on.
Then I loop on the tokens.
If a token is a number - I turn it to binary string.
If the token is translatable by vocabulary - I switch it to its binary representation.
Otherwise I print an error.
NOTE: if output should be padded with "0" - even though it is not specified in the question, I would use "0000".substring(n.length) + n
This is how I would do it:
var opcodes = {
Load: 1,
Store: 2,
Add: 3,
Sub: 4,
Equal: 5,
Jump: 6,
Halt: 7
};
var assemblyTextarea = document.querySelector("#assembly");
var machineTextarea = document.querySelector("#machine");
document.querySelector("#assemble").addEventListener("click", function () {
var instruction = assemblyTextarea.value.split(" ");
var operand =+ instruction[1].slice(1);
var opcode = instruction[0];
var code = opcodes[opcode] * 16 + operand;
var bits = ("0000000" + code.toString(2)).slice(-8);
machineTextarea.value = bits;
}, false);
See the demo here: http://jsfiddle.net/fs5mb/1/
The input should be formatted as follows: Load #15
I'm doing an assignment for a uni subject and having some trouble with javascript. I want to be able to change the value of an input field based on the value of another field. in short, the purpose is to input a quantity of a product in one field, and have the field next to it change to display the total amount of money required to purchase that quantity of products.
When I run my html, the quantity entered does not change the value of the cost field and im thinking there must be something wrong with my javascript.
Here is a copy of my javascript function, and the related html for it to execute within.
SCRIPT:
function calcRowWash(){
var theForm = document.forms["orderform"];
var x = theForm.getElementById("quantc").value;
var quantity = 0;
if(x.value!=""){
quantity = parseInt(x.value);
}
var totalC = (quantity*0.30);
document.getElementById("totc").value = totalC;
return;
}
HTML:
<td width = "90px" align ="left"><input type = "text" id ="quantc" name = "quantWash" size = "5" tabindex = "13" onblur="calcRowWash()"/></td>
<td width = "90px" align ="left"><input type = "hidden" id ="totc" name = "washtotal" size = "5" tabindex = "14" value=""/></td>
Thanks for the help!.
var theForm = document.forms["orderform"];
var x = theForm.getElementById("quantc").value;
This is redundant. IDs are unique on the entire document, so this will suffice:
var x = document.getElementById('quantc');
Also note that I removed the .value - this was the problem, because you then tried to get the value... of the value.
This works.
calcRowWash = (function(){
var x = document.getElementById("quantc");
var quantity = 0;
if (x.value!="") quantity = parseInt(x.value);
var totalC = (quantity*0.30);
document.getElementById("totc").value = totalC;
});
JSFiddle.
try with this code
function calcRowWash() {
var x = document.forms[0]['quantc'].value;
var quantity = 0;
if (x != "") {
quantity = parseInt(x);
}
var totalC = (quantity * 0.30);
document.forms[0]['totc'].value = totalC.toString();
}
Html Markup, I've changed the hidden type for an textbox and It works for me.
<td width = "90px" align ="left"><input type = "text" id ="quantc" tabindex = "13" onblur="calcRowWash()"/></td>
<td width = "90px" align ="left"><input type = "text" id ="totc" tabindex = "13"/></td> </div>
function calcRowWash(){
var theForm = document.forms["orderform"];
var x = theForm.getElementById("quantc").value;
var quantity = 0;
// Check if it is not empty
if(x.value != ""){
// Check if it is a valid number
if(x / x == 1){
quantity = parseInt(x.value);
}
}
var totalC = (quantity * 0.30);
document.getElementById("totc").value = totalC;
}
this works for me.
<form name="myForm" action="#" method="POST">
<input type = "text" id="quantc" name = "quantWash" size = "5" tabindex = "13" onblur="calcRowWash()"/>
<input type = "hidden" id ="totc" name = "washtotal" size = "5" tabindex = "14" value=""/>
</form>
function calcRowWash(){
var quantity = document.myForm.quantWash.value;
var price = 10.0;
document.myForm.washtotal.value = quantity * price;
}
The function doesn't comprise the parsing stuff. I just want to show how to read and set the value of both input fields.
You can use this JavaScript Code:
var inp = document.getElementById("inp"); // getting the Input ID
function change_value() {
inp.value = 'Your Value'; // <-- value
}
You can add Events:
inp.onfocus = change_value;
inp.onblur = another function with another action;
Good Luck Liam and Have a Nice Day.