multiplication inside an input with "*" operator - javascript

I am trying to get a multiplication entered in an input replaced by its solution.
Basicaly, when you enter 3*3 into the input, I would like my javascript code to replace 3*3 by 9.
Probably not so hard to obtain but I'm a total noob with javascript here. I get this so far, but I should miss a crucial point!
Thanks for your help :)
function multiply() {
var string = document.getElementById("mult").value;
var array = string.split("*");
var res = Number(array[0]*array[1]);
document.getElementById("res").value = res;
}
input{width:80px; text-align:right;}
input[readonly]{border:0;}
entrer: <input type="text" id="mult" onblur="multiply()">
<br>result: <input type="text" id="res" readonly>

Your code actually works as it is now. Just make sure you tab out of the input field after typing in the equation and you'll see it do its job. That's because your code is running on the blur event, which is when the focus leaves an element.
But, as far as your conversion code goes:
Number(array[0]*array[1])
Attempts to convert the product of array[0] and array[1], when what you need is to convert each array value to a number first and then do the math.
Number(array[0]) * Number(array[1])
Now, instead of Number(), you can just prepend a + to each value that needs conversion.
+array[0] * +array[1]
But, in reality, anytime you attempt to do multiplication, division or subtraction on strings, they are automatically converted to numbers, so you really don't even need that here.
Lastly, since you are just displaying the result and don't want the user to be able to modify it, just put it into a regular element, like a span instead of a form field element that you then have to set to readonly. Form fields are primarily for collecting information, not displaying it. When you do work with a non-form field element, you don't use the value property, you use .textContent (when there is straight text) or .innerHTML (when the string contains HTML to be parsed).
function multiply() {
var string = document.getElementById("mult").value;
var array = string.split("*");
var res = array[0] * array[1];
document.getElementById("res").textContent = res;
}
input{width:80px; text-align:right;}
input[readonly]{border:0;}
entrer: <input type="text" id="mult" onblur="multiply()">
<br>result: <span id="res"></span>

Related

Replace part of a string with another string javascript

what I have is 3 text boxes. The first one a user enters a string. The second box they enter part of the first string they want to replace. The third text box is the string that is to do the replacing.
I'm trying to use the replace() method but I dont think Im using it right or i should be using something else.
html:
<form>
Enter a string:<input type="text" id="user_string"><br>
Enter portion of previous string to be replaced: <input type="text" id="replace_string"><br>
Enter new string: <input type="text" id="add_string"><br>
<input type="button" value="Execute" onclick="BaitAndSwitch()"><br>
Result: <input type="text" id="req_4_results"><br>
</form>
Javascript:
function BaitAndSwitch(){
// create variables for the user entered data
var UserString = document.getElementById("user_string").value;
var ReplaceString = document.getElementById("replace_string").value;
var AddString = document.getElementById("add_string").value;
var Results = UserString.replace(ReplaceString, Addstring);
if (UserString.indexOf(ReplaceString) > -1) {
Document.getElementById("req_4_results").value = Results;
}
else{
alert("Something went wrong! Please check the data you entered.")
}
}
I know I'm doing something wrong. Maybe the use of variables in the .replace() method? Or maybe the if... using indexOf line?
I was essentially trying to set it up where it would check UserString with the value of ReplaceString and if it matched, it would then execute the replace() method and show results to the given HTML element. Else if the ReplaceString didn't match any thing from UserString, it would alert the user something was wrong and to check it.
JavaScript is cAsE SeNsItIvE. Please note that Document is not the same as the document object. Please use the below line:
document.getElementById("req_4_results").value = Results;
Oh and yes, as pointed out by blex, you have another typo too:
var Results = UserString.replace(ReplaceString, Addstring);
//-------------------------------------------------^ should be S
More Info: In the console, if you try both, see the result you get:
typeof Document
// "function"
typeof document
// "object"
On a side note, please do not use such Naming Conventions. Looks like you are migrating from Visual Basic.
Note that the replace() method does not modify the string that you call it on.
In your line of code:
var Results = UserString.replace(ReplaceString, Addstring);
The value of UserString will not changed as a result of having called replace() on it.
In your conditional statement:
UserString.indexOf(ReplaceString) > -1
If it is true, it means that UserString still contains at least one instance of ReplaceString within it.
That makes sense, because you wouldn't have modified UserString yet. If you want to make sure that Results no longer has any occurrence of ReplaceString, then you want to throw an error only if the following condition is true:
Results.indexOf(ReplaceString) > -1

Alternative in regular expression's ending

I have the following DOM structure:
<form>
<input type="text" id="a">
<button>Submit</button>
</form>
or:
<form>
<input type="text" id="a">
</form>
which one depends on what user have done, it's created dynamically.
I want to be able to add another input right below the previous one (it can not exist yet and be the first one). To do that, I wanna get all text until the place I'm adding new input. How can I get that text using regex?
I tried the following:
'(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]'
But it doesn't work, because it displays empty string as a result.
var afterRegex = new RegExp('(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]', 'i');
var appendAfter = $(".downloadCode textarea").val().match(afterRegex)[1];
alert(appendAfter);
I'm a little confused by your code, but, based on what you've said (and that you've tagged your question with jQuery), I think that you can accomplish what you are trying to do with this code:
var $newInput = **CREATE_YOUR_NEW_INPUT_ELEMENT_HERE**;
var $form = $("form");
var $lastInput = $form.find("input:last");
// no inputs, make the new input the first element in the form
if ($lastInput.length < 1) {
$form.prepend($newInput);
}
// at least on existing input, add the new input after the last one
else {
$lastInput.after($newInput);
}
You should not parse HTML using Regexp. No, seriously.
That being said, the correct syntax for multi-character alternatives is (?:alternativeA|alternativeB):
(.*?)(?:<button.*?>Submit<\/button><\/form>|<\/form>)
Note that this does not work if you have whitespace characters in between. Yet another reason not to use Regexps here.

Trying to multiple two numbers entered in text fields and alert the answer using jquery

Very new to javascript and jquery. Attempting an exercise and came up with this code which I was hoping would take the two numbers a user enters into text fields and on clicking the multiply button, it would alert() the answer.
<body>
<script>
$(document).ready(function(){
var first = $('#first').value;
var second = $('#second').value;
$('#multiply').click(function(){
alert(first*second);
}); // end click
}); // end ready
</script>
First Number:
<input type="text" id="first"><br >
Second Number:
<input type="text" id="second"><br >
<input type="button" id="multiply" value="Multiply">
<input type="button" id="divide" value="Divide">
</body>
I'd suggest:
$(document).ready(function(){
$('#multiply').click(function(){
var first = parseFloat($('#first').val());
var second = parseFloat($('#second').val());
console.log(first*second);
}); // end click
}); // end ready
val() is used to get the value from a jQuery object (or the value of the first element of a jQuery collection),
parseFloat() is used to convert the <input/> elements' string into a number.
Incidentally, I'm using console.log(), instead of window.alert(), in order to be less frustrating the user. But, obviously, change that to your own taste (but logging to the console doesn't require a user-action to dismiss).
References:
JavaScript:
parseFloat().
jQuery:
val().
There is no value property in a jQuery object, use the val method to get the value from the inputs:
var first = $('#first').val();
var second = $('#second').val();
Right now you have the code for getting the values when the page loads, but you should get the values when the click happens:
$(document).ready(function(){
$('#multiply').click(function(){
var first = $('#first').val();
var second = $('#second').val();
alert(first * second);
}); // end click
}); // end ready
You are using implicit conversion from strings to numbers when you do the multiplication. You might want to explicitly parse the strings, it's good practice to make sure that the data is of the correct type rather than relying on implicit conversions. If you for example want to add numbers, the implicit conversion won't work there, as the + operator also is used to concatenate strings. Use the parseInt or parseFloat methods to parse strings into numbers. Example:
var first = parseInt($('#first').val(), 10);
var second = parseInt($('#second').val(), 10);
When you grab the value of a text field, the result is text. Not a number. You can parse the value into a number with the (globally available) parseFloat function (Or the parseInt function if there is no fractional value to the numbers).
var first = parseFloat($("#first").val());
var second = parseFloat($('#second').val());
$('#first') is a jQuery object, so you should use the .val() method. On the other hand, you are setting the variables when the DOM is ready, so it's not updating it when the user clicks.
$(document).ready(function () {
var first, second;
$('#multiply').click(function () {
first = $('#first').val();
second = $('#second').val();
alert(first * second);
});
});
In other things, your script tags should be at the end of the body. Script parsing is synchronous so the browser takes more time to get the DOM ready.
Have fun! :)

JavaScript populating and clearing <input> textbox

I got 6 "textboxex" and an Array with them.
<input id="slot0" type="text" /> id from 0 to 5, also Array named "slotarray". I want arrray and textboxes to be bound slotarray[0] with input id="slot0" etc.
First i needed function that will find first empty field in array (no matter if corresponding textbox is empty - but should) and put there string (short string - shortcode like "abc" or "sp1").
This function also need to populate bound textbox with long string.
If slotarray[2] == 'abc' then with the same number in ID (here be id="slot2") need to contain long string like "Abrasive Brilliant Conexant".
Here what i got
click to populate
and then function
function populate(shortstring,longstring) {
for (var i=0; i<6; i++) {
if (slotarray[i] == '') {
slotarray[i] = shortsrting;
slotid = 'slot' + i;
document.getElementById(slotid).value = longstring;
break;
}
}
}
With clearing at the moment of creating: ( Array('','','','','','') ), and textbox .value=''; its working as it should.
But then i figured out that i need function to clear textbox and bound array field. Not all but one specific for one clic. So instead of 6 functions i start to wrote
clear this field
for each of textbox, with different numbers and ids ofcourse, and clearing function:
function clear(arrayid, slotid) {
slotarray[arrayid] = '';
document.getElementById(slotid).value = '';
}
But this function do not clearing textbox neither array. I see that textbox has text, and i know that array isn't cleared because first function works finding first empty object...
What am i doing wrong here? its definition of "empty"/"cleared" filed/textbox? maybe i need to use more complex conditions? maybe it is something else.
Maybe i don't need array (i can manage to get rid of short-codes) and just make functions work only on textboxes?
Ok - i prepared jsfiddle demo with this, but even populating don't work..
http://jsfiddle.net/BYt49/11/
You can't use the keyword clear because refers to the (deprecated) function document.clear; so try to change the name of your "clear" function.
Ok, whatever you have written is fine. Just change to way you call your javascript.
Here is jsfiddle: http://jsfiddle.net/BYt49/20/

Using jQuery to display a value to 2 decimal places in an input box while retaining more precision [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: formatting number with exactly two decimals
Maybe I'm going about this the wrong way, but I have some javascript which is filling up some text inputs with numbers like 12.434234234. I want the text input to only display 12.43, but I'd like it's value to remain as 12.434234234.
Is this even possible? If not, what would be the best work-around?
Thanks!
John.
--
Although there were some very good answers here, I was looking for something like 'why don't you just use this clever one liner thing..' - hence I've ticked the most basic approach which is to just use an extra field. Thanks though! Marked up all answers.
num = 12.434234234;
result = num.toFixed(2); // returns 12.43
You can store the fine-grained values in hidden fields, and trim the ones displayed for the user.
You could store the value of the input as data of the input (using jQuery), format it onload and then replace the value during submit like so:
http://jsfiddle.net/magicaj/8cdRs/1/
HTML:
<form id="form">
<input type="text" class="formatted-number-input" value="12.434234234" />
</form>
JS:
$(".formatted-number-input").each(function() {
var value = $(this).val();
$(this).data("originalValue", value);
var roundedValue = value.toFixed(2);
$(this).val(roundedValue);
});
$("#form").submit(function() {
var formattedInput = $(".formatted-number-input");
formattedInput.each(function() {
var originalValue = $(this).data("originalValue");
$(this).val(originalValue);
});
});
There are multiple ways to solve this problem:
1. Create hidden field, store 12.434234234 in it and display formatted value in textfield.
2. Store original 12.434234234 using jquery.data() and display formatted value in textfield.

Categories

Resources