Retrieving Input Values from a Text Box - javascript

I need to make a box so that when the user enters a value of one through 6, it rolls that many dice. I'm a complete beginner to javascript and any help would be greatly appreciated.
Here's my function:
function NumberValue() {
for (i = 0; i <['randNumber']; i++){
var numberRoll = Math.floor(Math.random() * 6) + 1;
var userNumber = '../images/die' + numberRoll + '.gif';
myNewTag = "<img id='dieImgRandom' src='" + userNumber + "'>"
document.getElementById('dieDivRandom').innerHTML += myNewTag;
And here is my body element:
<h1>Why don't you pick please?</h1>
<div id="dieDivRandom" style="text-align:center">
<p>
<div id="dieImageRand">
<img id="dieImgRandom" alt="die image" src="../images/die1.gif">
<br>
<input type="text" id="randNumber" size=20 value="Enter 1 through 6">
<input type="button" value="Click to Roll" onclick="NumberValue();">
</div>
The function needs to allow a user to submit the number one, two, three, four, five, or six, and that many images need to display on the screen. The images a relocated in my images folder, so relative links will work just fine. That's actually what I need to use. Thank you.

Replace:
for (i = 0; i <['randNumber']; i++){
With:
for (i = 0; i <document.getElementById('randNumber').value; i++) {
The <input /> tag can be accessed by using either of the following:
document.getElementById('inputId').value;
document.formName.inputName.value
Finally, your code becomes:
function NumberValue() {
for (i = 0; i < document.getElementById('inputId').value; i++) {
var numberRoll = Math.floor(Math.random() * 6) + 1;
var userNumber = '../images/die' + numberRoll + '.gif';
myNewTag = "<img id='dieImgRandom' src='" + userNumber + "'>"
document.getElementById('dieDivRandom').innerHTML += myNewTag;
}
}

Use this to read values from textbox
function NumberValue() {
var ranNum = document.getElementById('randNumber').value;
for (i = 0; i <ranNum ; i++){
}
}
EDIT:
If you want to validate the Entered number
add this block of code
function NumberValue() {
var ranNum = document.getElementById('randNumber').value;
if(ranNum < 1 || ranNum > 6) {
alert("Please enter number from 1 to 6 only");
return false;
}
for (i = 0; i <ranNum ; i++){
}
return true;
}

Related

Why is my character counter not excluding spaces?

I am making a character counter with HTML, CSS, JS. I got the counter working, but I have a checkbox that should get the length of the input without the spaces, but it is not working. Please check my code and tell me what's wrong.
function char_count(str, letter) {
var letter_Count = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == letter) {
letter_Count += 1;
}
}
return letter_Count;
}
function countChars(obj) {
var length = obj.value.length;
var output = document.getElementById("chars");
var dis = document.getElementById("removeSpace");
if (dis.checked) {
var spaces = char_count(obj, " ");
length = length - spaces;
output.innerHTML = length + ' characters';
} else {
output.innerHTML = length + ' characters';
}
}
<h1> Character Counter </h1>
<textarea id="input" onkeyup="countChars(this)" placeholder="Enter your text here..." autofocus></textarea>
<input type="checkbox" id="removeSpace">
<label for="removeSpace" onclick="countChars(document.getElementById('input'))">Don't Include Spaces</label>
<span id="chars">0 Characters</span>
You could make the code more simpler. Moreover, you have placed the checkbox outside the label that has onclick="countChars(document.getElementById('input'))", that's why the condition dis.checked in js does not find the checkbox as checked. Place the checkbox inside the label.
The whole simplified code would be like this,
<h1> Character Counter </h1>
<textarea id="input" onkeyup="countChars(this)" placeholder="Enter your text here..." autofocus></textarea>
<label for="removeSpace" onclick="countChars(document.getElementById('input'))">
<input type="checkbox" id="removeSpace">
Don't Include Spaces</label>
<span id="chars">0 Characters</span>
<script>
function countChars(obj) {
var length = obj.value.length;
var output = document.getElementById("chars");
var dis = document.getElementById("removeSpace");
if (dis.checked) {
length = obj.value.replace(/\s/g, '').length
}
output.innerHTML = length + ' characters';
}
</script>

How to find if there is a space in a string... tricky

I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}

Parsing JSON data using JavaScript push - want to prevent automatically closing divs

I'm working on parsing JSON data and converting it to html form.
I'm using the javascript push function, which I thought would push the data into the array I've designated it to in the order I push it. However, whenever I push a new div element, it is automatically closed after being pushed making the html come out in a different order I want. Is there a way I can prevent this?
JavaScript:
$(function(){
var container = $('.panel-body');
var jsonObj = $.parseJSON('{"fields":[{"label":"Nafn form / Form name","field_type":"sFormName","required":false,"field_options":{"size":"small"},"cid":"c2"},{"label":"Spurning 1 ","field_type":"QuestionText","required":false,"field_options":{"size":"small"},"cid":"c5"},{"label":"Spurning 2","field_type":"QuestionCheckbox","required":false,"field_options":{"options":[{"label":"","checked":false},{"label":"","checked":false}]},"cid":"c9"},{"label":"Spunring 4","field_type":"QuestionRadio","required":false,"field_options":{"options":[{"label":"Val","checked":false},{"label":"VAl ","checked":false},{"label":"Val","checked":false}],"include_other_option":false},"cid":"c13"},{"label":"Spurning með multi","field_type":"QuestionMultiBegin","required":false,"field_options":{"options":[{"label":"","checked":false},{"label":"","checked":false}]},"cid":"c17"},{"label":"Spurning","field_type":"QuestionDropdown","required":false,"field_options":{"options":[{"label":"Val","checked":false},{"label":"Val","checked":false},{"label":"Val","checked":false}],"include_blank_option":false},"cid":"c21"},{"label":"Skráning","field_type":"Registration","required":false,"field_options":{"options":[{"label":"Notendanafn / Username"},{"label":"Lykilorð / Password"}],"include_blank_option":false},"cid":"c25"}]}');
var body = [];
var headerData = jsonObj.fields;
console.log(headerData);
for (var i = 0; i < headerData.length; i++) {
if(jsonObj.fields[i].field_type == "sFormName") {
body.unshift("<div class='panel panel-default panel-element'><div class='panel-heading'>" + jsonObj.fields[i].label)
} else {
body.push("<div class='panel panel-default panel-element'><div class='panel-heading'>" + jsonObj.fields[i].label);
}
if (jsonObj.fields[i].field_type == "QuestionText") {
body.push("<div class='panel-body'><textarea class='large-text form-control'></textarea></div>");
} else if (jsonObj.fields[i].field_type == "QuestionParagraph") {
body.push(jsonObj.fields[i].field_options.description);
} else if (jsonObj.fields[i].field_type == "QuestionDropdown") {
var data = jsonObj.fields[i].field_options.options;
body.push("<div class='panel-body'><div class='dropdown'><button class='btn btn-default dropdown-toggle' type='button' data-toggle='dropdown' id='dropdownMenu1' aria-haspopup='true' aria-expanded='true'>" + jsonObj.fields[i].field_options.options[0].label + "<span class='caret'></span></button>");
body.push("<ul class='dropdown-menu' aria-labelledby=dropdownMenu1'>");
for(var j = 0; j < data.length; j++) {
body.push("<li><a href='#'>" + jsonObj.fields[i].field_options.options[j].label + "</a></li>");
}
body.push("</ul></div></div>");
} else if (jsonObj.fields[i].field_type == "QuestionRadio") {
var data = jsonObj.fields[i].field_options.options;
body.push("<div class='panel-body'>");
for(var j = 0; j < data.length; j++) {
body.push("<div class='radio'><div class='controls'><input type='radio' name='radio'></input>" + jsonObj.fields[i].field_options.options[j].label);
}
body.push("</div></div></div></div>");
} else if (jsonObj.fields[i].field_type == "Registration") {
body.push("<div class='panel-body'>");
body.push("<div class='form-group'><form class='reg-form' role='form'><div class='form-group'><label for='email'>" + jsonObj.fields[i].field_options.options[0].label + "</label>");
body.push("<input type'email' class='form-control' id='email'></div>");
body.push("<div class='form-group'><form class='reg-form' role='form'><div class='form-group'><label for='pwd'>" + jsonObj.fields[i].field_options.options[1].label + "</label>");
body.push("<input type'password' class='form-control' id='pwd'></div>");
body.push("<div class='checkbox'><label><input type='checkbox'> Muna mig / Remember me</label></div></form></div>");
}
$(container).html(body);
}});
As you can see, I wrote the code assuming that I would have to push an ending div to each element that I'd opened, however that seems to be ignored.
The problem here is that you're trying to pass the body array to the html method, however you should instead concatenate all strings inside of it, the pass it.
Like so:
var htmlMarkup = body.reduce(function(){
return prev + current;
}, '');
or use 'join' as suggested by Hacketo, since it's less verbose:
var htmlMarkup = body.join('');
$(container).html(htmlMarkup);

How to add dynamic textbox in java script

I need to create text box using JavaScript. I coded as below:
<script>
function _(x) {
return document.getElementById(x);
}
function popuptxt() {
var i = _("no_room").value;
for(a = 1; a <= i; a++) {
my_div.innerHTML = my_div.innerHTML + "Room number for " + a + "<br><input type='text' name='mytext'+ i><br>"
}
}
<script>
HTML file:
<input type="text" style="width:200px;" id="no_room" onChange="popuptxt()" required>
<div id="my_div"></div>
It displays number of textbox when I type a number, but I need to clear them when I type another number.
Just reset the content of you block each time :
<script>
function _(x) {
return document.getElementById(x);
}
function popuptxt() {
my_div.innerHTML = "";
var i = _("no_room").value;
for(a = 1; a <= i; a++) {
my_div.innerHTML = my_div.innerHTML + "Room number for " + a + "<br><input type='text' name='mytext'+ i><br>"
}
}
</script>
Just add my_div.innerHTML = ""; before the for loop in popuptxt(). That way it will be cleared each time its called.

How to get specific radio value from PHP

I'm not getting the right value from my radio buttons on my 'Thank You' page.
I want that after my user end the payment and he get redirected to the thank you page some values from the filled form to be posted there. And I have archive just that with this script on the form.php file:
<script type="text/javascript">
function CookieTheFormValues() {
var cookievalue = new Array();
var fid = document.getElementById(FormID);
for (i = 0; i < fid.length; i++)
{
var n = escape(fid[i].name);
if( ! n.length ) { continue; }
var v = escape(fid[i].value);
cookievalue.push( n + '=' + v );
}
var exp = "";
if(CookieDays > 0)
{
var now = new Date();
now.setTime( now.getTime() + parseInt(CookieDays * 24 * 60 * 60 * 1000) );
exp = '; expires=' + now.toGMTString();
}
document.cookie = CookieName + '=' + cookievalue.join("&") + '; path=/' + exp;
return true;
}
</script>
And than by putting this script on the thank you page :
<?php
$CookieName = "PersonalizationCookie";
$Personal = array();
foreach( explode("&",#$_COOKIE[$CookieName]) as $chunk )
{
list($name,$value) = explode("=",$chunk,2);
$Personal[$name] = htmlspecialchars($value);
}
?>
So far so good I get all right values from other inputs but from radios I get always the last in class name value? This mean for eg if I have this code:
<input type="radio" name="emotion" id="basi" value="Basic Pack" />
<input type="radio" name="emotion" id="deli" value="Deluxe Pack" />
<input type="radio" name="emotion" id="premi" value="Premium Pack"/>
And in the Thank you page I put this code for eg
Thank you for chosing <?php echo(#$Personal["emotion"]); ?>
I get always this Thank you for choosing Premium Pack even when i check the basic or deluxe radio why this?
Your loop:
for (i = 0; i < fid.length; i++)
{
var n = escape(fid[i].name);
if( ! n.length ) { continue; }
var v = escape(fid[i].value);
cookievalue.push( n + '=' + v );
}
will push all three of the radios into your cookie value. Each one will overwrite the previous, because they have the same name. So ultimately you're left with the value 'Premium Pack' mapped to the "emotion" name. You need to check if the radio is selected before you push the val, maybe something like:
for (i = 0; i < fid.length; i++)
{
var n = escape(fid[i].name);
if( ! n.length ) { continue; }
var v = escape(fid[i].value);
// Only push in the selected emotion radio button
if (n == "emotion") {
if (fid[i].checked == true) cookievalue.push( n + '=' + v );
}
else cookievalue.push( n + '=' + v );
}

Categories