Display Form Input as Stylized String - Javascript - javascript

I am trying to take input from a number field and display it somewhere else on the page.
Here is my HTML
<input id="dollar" type="text" name="mytextfield2" onkeyup="updateDollarDisplay();">
<div id="dollarValue"></div>
and my javascript
function convertDigitsToArray(number){
var s = parseInt(number).toString(10).split("").map(Number);
return s;
}
function updateDollarDisplay() {
var amount = $('#dollar').value;
var a = convertDigitsToArray(amount);
console.log(a[0]);
$('#dollarValue').text(a[0]);
}
Running the exact code in a javascript interpreter works fine, it gives me each digit as an element in the array. When I try to do the same through the HTML page it gives me NaN each time. Any ideas?
Fiddle here: http://jsfiddle.net/7mzo8eb5/2/ I'd like it to show to input in the grayed div on each input.

The problem is with var amount = $('#dollar').value;
value is not an attribute, but val is a function. Should be: var amount = $('#dollar').val();

Related

Building a calculator using html JavaScript which takes values from two input tags and returns final answer on clicking submit button

Calculator which takes numbers written in input tag by users and then add them on clicking submit and shows result.
var numOne = document.getElementById("first");
var numTwo =
document.getElementById("second");
var submit = document.getElementById("submit");
var added = document.getElementById("answer");
submit.addEventListner( function(){
var one = numOne.value;
var two = numTwo.value;
added.innerHTML = one + two;
})
Please tell me the mistake
html
<input type="number" id="a">
<input type="number" id="b">
<input type="submit" id="submit">
<h1 id="answer"></h1>
Javascript
var submit = document.querySelector('#submit');
var answer = document.querySelector('#answer');
submit.addEventListener('click', () => {
var a = document.querySelector('#a').value;
var b = document.querySelector('#b').value;
answer.textContent = Number(a) + Number(b);
})
This is pretty straightforward but can be expanded upon to validate input properly and do other calculations.
Firstly, if you take a look at the html, you can see two number input fields and one submit button. Note that I have given them all IDs so that we can select them in our JS file. I have also provided an empty h1 element in which we will display the answer of our calculation.
In the JS file we are just listening for a click event on the submit button at which point, we capture the values entered into your input fields and add them together after coercing their type to numbers.
Finally, we return the sum of these values to the DOM as the textContent of the h1 element with id="answer"

How do a maintain an accurate character count between input from separate fields using JS?

I am using a form to build a block of text, the final output of which needs to be kept under a certain character count.
For the user, I need to be able to provide real-time character counting so they can adjust their entries as appropriate.
Basic HTML would be as follows:
<form>
<input type="text" id="#input1">
<input type="text" id="#input2">
</form>
<div class="character-counter">0</div>
However my JS/jQuery is not working very well: while it is outputting a counter in real time, it seems to be concatenating the final results in the output despite me parsing the variables as integers.
$('#input1').keyup(function() {
// Variables
var currentCharCount = parseInt($('.character-counter').text());
var fieldLength = parseInt($(this).val().length, 10);
var newCharCount = fieldLength + currentCharCount;
// Counter output
$('.character-counter').text(Number(newCharCount));
});
$('#input2').keyup(function() {
// Variables
var currentCharCount = parseInt($('.character-counter').text());
var fieldLength = parseInt($(this).val().length, 10);
var newCharCount = fieldLength + currentCharCount;
// Counter output
$('.character-counter').text(Number(newCharCount));
});
The correct solution will update the '.character-counter' div with the correct total character count between the fields every time a character is typed or deleted or pasted in.
Thanks!
You don't want the old value of the character-counter element at all, you purely want to use the lengths of the text in the two inputs. Separately: Don't use keyup, use input. (What if the user right-clicks and pastes? No keyup occurs...)
Separately, the id attributes of your input fields are incorrect: They shouldn't have the # on them.
So (see comments):
// You can hook the event on both fields with the same call
// Note using `input`, not `keyup`
$("#input1, #input2").on("input", function() {
// Get the length of each input's current value, then put it
// in the .character-counter div
$('.character-counter').text($("#input1").val().length + $("#input2").val().length);
});
<form>
<input type="text" id="input1">
<!-- No # here --------^ -->
<input type="text" id="input2">
<!-- Nor here ---------^ -->
</form>
<div class="character-counter">0</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Get the tag name of a form input value

How does one get the .tagName of a value passed in an HTML form input? This is to check whether the value that has been passed is an 'iFrame'. The input is to only accept iframes
For example:
//HTML
<input type="text" id="iFrame">
<button id="butt">Push</button>
//JavaScript
document.getElementById("butt").onclick = function(){
var iframe = document.getElementById("iFrame").value;
console.log(iframe.tagName);
}
I think you are looking for
var iframe = document.getElementsByTagName("iFrame")
I perhaps did not ask the question in the best way, initially.
I wanted to check if the value passed in the input field was an "iframe" (the input is to only accept iFrames). Since .value returns a string and not an HTML tag, getting the tag name through basic methods would not work. I needed another way.
For anybody else who needs a quick solution, this is how I managed to do it:
document.getElementById("submit").onclick = function(){
var iframe = document.getElementById("iFrame").value;
var check1 = iframe.match(/iframe/g);
var check2 = iframe.match(/frameborder/g);
var check3 = iframe.match(/http:/g);
var check = check1.length + check2.length + check3.length;
if (check === 4) {
alert("good!");
}
}

How do you return data from javascript into a html form?

I was wondering if anyone can help? What I am trying to do is retrieve the word count from javascript code into a form and then pass it into php along with the rest of the form which will check that the word count is a certain length or else it won't be submitted.
The javascript is as follows.
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
My problem is returning wordCount into a hidden field in a form. I am not too good with javascript and am not sure how to modify this code to make it work. The rest I can figure out but am stuck here. Thank you for your help, it is greatly appreciated.
$('#wordCount').val(wordCount);
$('#totalChars').val(totalChars);
$('#charCount').val(charCount);
$('#charCountNoSpace').val(charCountNoSpace);
Use .val() instead of .html(), because .val() refers to the value of an input field.
Your HTML inside the form should include a hidden input field:
<input type="hidden" id="word_count" name="word_count" value="0" />
Then inside your JS:
$('#word_count').val(wordCount);
All together embedded inside your function:
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#word_count').val(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
If you have INPUT fields in your form, use val()
$('#wordCount').val(wordCount)
That would work for a field like this:
Be aware that there's a difference between "id" and "class". jQuery allows you to select elements based on their properties. The "id" property gets selected with "#", just like you'd do it in CSS. So make sure you have that "id='wordCount'" defined in your hidden field.
Have a look at this http://www.hscripts.com/scripts/JavaScript/word-count.php
There are plenty of examples online, just google "javascript count words in textbox"
Some imporntant notes:
A very long string with no spaces is still 1 word so don't forget to set the max length for fields
If you are doing this as a sort of validation be aware of the fact that you can not trust a form field because it can be easily manipulated, so don't forget to check the word count on the server side after the form is submitted.
The Code that you are showing is not just javascript it also includes jquery, please make sure you included jquery
<script src = "http://code.jquery.com/jquery-1.11.1.min.js"></script>
$('#field').val('asdf'); //Sets Value of a input type="text"
$('#field').html('sadf'); //Sets the html of a div
Using javascript you use either value for a input or innerHtml for a div or other text based element
document.getElementById('field').value = 'asdfsadf';
document.getElementById('field').innerHtml= 'asdfsadf';
Also instead of using a form submit consider using jquery $.ajax(there is nothing wrong with form submits but there are benefits to knowing jquery as well such as you came make async requests
http://api.jquery.com/jquery.ajax/
You will want to use a hidden field such as the following and have it in the form
<form id="myform" action='posttome.php'>
<input type="hidden" id="wordCount"/>
<input type="submit" value="sbumit"> //Submits Form
</form>
Then set its value by using of of three methods, a an elements html, an elements value, or a javascript variable $('#wordCount').val()
$('#wordCount').val($('#wordCountSoruceDiv').html()); // Sets the value to another divs html
$('#wordCount').val($('#wordCountSourceInput').val()); // Sets the value to another inputs value
$('#wordCount').val(wordCountVariable); // Sets the value to a variable

Stop a page from refreshing after firing a function

I've been tasked with building a very simple app that that has a series of dropdowns in rows of 2, when 2 are selected, a simple functions concatenates the 2 values and gives an output next to them like so:
dropdown1 dropdown2 Output
What I'm trying to get is, once the second dropdown value is chosen the function runs and displays the output where it says output. But currently, what seems to happens is the output is displayed in a new window.
Here's what I have so far (HTML):
<form>
<select id="test">
<option>Arena/Quantum Barcelona LTBC</option>
<option>Arena/Quantum Spain LTES</option>
</select>
<select id="name" onchange="tryThis()">
<option>Name</option>
<option>Name1</option>
</select>
</form>
JavaScript:
function tryThis() {
var string, string1 = '';
var e = document.getElementById("test");
string = e.options[e.selectedIndex].text;
var a = document.getElementById("name");
string1 = a.options[a.selectedIndex].text;
document.write(string+'_'+string1);
}
Am I making this more difficult than it needs to be?!
That's because document.write clears the page before displaying something. You should never need to use that function.
Instead, you could append it to e.g. the body:
document.body.appendChild(
document.createTextNode(string + '_' + string2)
);
Have you noticed that your JS function is called tryThis() and on the event handler you're calling tryThsis()
However in your case I'd refrain from using document.write, good alternatives are appending to the body or having a DIV and changing the innerHTML of that DIV
First put an id on your form so that it is easier to access.
var a = (function () {
var myForm = document.getElementById("myForm"),
magic = function () {
var a = myForm.getElementsByTagName("select"),
b,
c = [];
for (b = a.length - 1; b > -1; b -= 1) {
c.push(a[b].value);
}
alert(c.join(" ") + " output");
};
myForm.onclick = magic;
}());
You were not specific as to what the extra "output" is supposed to be or how you want the data returned, but here you go. Instead of using an alert you could push the result into the value of a different form element. Do not use document.write as this cannot be deferred. If you attempt to defer a document.write operation it will replace the entirety of the body contents of the current page.

Categories

Resources