Add string from textbox input - javascript

i have a textbox1 which input by user and textbox2 for user to input numbers which can automatically generate textbox1 value into multiple string such as example below:
Txtbox1 = ABC12345
Txtbox2 = 3
Result will be
ABC12345-1
ABC12345-2
ABC12345-3

You can try using something like this below, but kinda hard to make it 100% as you want, since you haven't shown any HTML.
$("[id^=Txbox]").keyup(function() {
var empty = $("[id^=Txbox]").filter(function() {
return $.trim($(this).val()).length == 0
}).length == 0;
if (empty) {
var str = $("#Txbox1").val();
var number = $("#Txbox2").val();
var arr = [];
for (i = 0; i < number; i++) {
arr.push(str + "-" + i)
}
console.log(arr)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Txbox1" />
<input id="Txbox2" type="number" />

You can just use button and apply click event.
function getString() {
var finalString = [];
var t = $("#textbox1").val()
var n = $("#textbox2").val();
if (t.toString().trim() != "") {
for (i = 0; i < n; i++) {
finalString.push(t + "-" + (i + 1))
}
}
console.log(finalString)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text : <input type="text" id="textbox1"><br><br> Number : <input type="text" id="textbox2">
<button type="button" onClick="getString()" id="textbox1">Get</button>

Related

print 1 to 5 and even and odd in HTML and JavaScript

I have to create a html page which satisfy below requirement-
1. print 1 to 5 with another array
2. take number input from textbox then print on page whether it is Even or Odd.
I have create a page but it is not working as desired.
<HTML>
<HEAD>
</HEAD>
<BODY>
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<input type="text" name="result" id="result" readonly="true"/>
<SCRIPT>
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = if((value % 2) == 0) {"Even"} else {"Odd"}*/
//if(value % 2 == 0) document.write("Even")
//document.write(value);
//document.getElementById("demo").innerHTML = res;
readonly.value=res;
}
//document.write("Hello World!");
</SCRIPT>
</BODY>
</HTML>
Could someone please help me with the code.
please see the updated solution
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = value % 2 == 0 ? "Even" : "Odd";
document.getElementById("result").value=res;
}
//document.write("Hello World!");
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<input type="text" name="result" id="result" readonly/>
Updated code
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = value % 2 == 0 ? "Even" : "Odd";
document.getElementById("result").innerHTML=res;
}
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<p id="result"></p>
Update2
Replace
<p id="result"></p>
with
<span id="result"></span>
There is a problem with the way you are assigning res, it should be as follows:
var res = value % 2 == 0 ? "Even" : "Odd";
Alternatively you can use an if statement if you want like so:
var res = "Odd";
if(value % 2 == 0) {
res = "Even";
}
In addition, there is also an issue with this line:
readonly.value=res;
In this case, readonly does not exist. You probably mean to do this:
document.getElementById("result").value = res;

Regex - match character only once - then ignore

I went through a lot of questions and couldn't solve my problem.
I need to match a number of special characters, but only once.
HTML:
<form class="FillIn Rearrange">
<input data-correctanswer="ça" type="text">,
<input data-correctanswer="ça" type="text">
<input data-correctanswer="vé" type="text">
<input data-correctanswer="bién" type="text">
</form>
This JS currently returns ALL ç, and é, but I need 1 max. of each:
var buttons = '';
$('.FillIn input').each(function () {
var corrAns = $(this).attr('data-correctanswer');
for (var i = 0; i < corrAns.length; i++) {
if (corrAns[i].match(/[éç]/g)) {
buttons += '<button>' + corrAns[i] + '</button>';
}
}
});
fiddle
Currently returns ççéé (all occurrences)
Need it to return çé (one of each).
Need a scalable solution, i.e. .match(/[éçdfga]/g) (or any extra letter)
Here's how you can do it:
var buttons = '';
function createButtons(lettersToMatch){
$('.FillIn input').each(function () {
var corrAns = $(this).attr('data-correctanswer');
for (var i = 0; i < corrAns.length; i++) {
var match = corrAns[i].match(new RegExp(lettersToMatch));
if (match) {
buttons += '<button>' + corrAns[i] + '</button>';
lettersToMatch = lettersToMatch.replace(match[0], "");
}
}
});
}
//Testing
createButtons("[éèçêïë]");
$("body").append( buttons );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="FillIn Rearrange">
<input data-correctanswer="çaï" type="text">,
<input data-correctanswer="ça" type="text">
<input data-correctanswer="vé" type="text">
<input data-correctanswer="bién" type="text">
</form>
It looks like you want to end the for loop as soon as you get a match, so throw in a break statement:
var buttons = '';
$('.FillIn input').each(function () {
var corrAns = $(this).attr('data-correctanswer');
for (var i = 0; i < corrAns.length; i++) {
if (corrAns[i].match(/[éç]/g)) {
buttons += '<button>' + corrAns[i] + '</button>';
break;
}
}
});
You simply need to remember what you have already found and not process it:
var buttons = '';
var found = []; // this remembers what we have already found
$('.FillIn input').each(function () {
var corrAns = $(this).attr('data-correctanswer');
for (var i = 0; i < corrAns.length; i++) {
var m; // hold the match
if (m = corrAns[i].match(/[éç]/)) {
// not found yet
if(found.indexOf(m[0]) == -1) {
found.push(m[0]) // remember it's been found
buttons += '<button>' + corrAns[i] + '</button>';
}
}
}
});

Converting form text in HTML into an array in JS

I am attempting to create an online solver for the maximum subarray problem.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
I planned on taking user-input numbers from a textbox and converting them into an int array in JS, however my JS does not seem to be running at all.
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<title> findMaxSum </title>
<script src="findMaxSum.js" type="text/javascript"></script>
</head>
<body>
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p> Enter numbers with spaces, i.e. "1 2 3 4 5": </p>
<input type="text" id="array"> <br>
<button id="sum">findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is: </p>
</body>
</html>
and my JS. note: the map(function(item)) part of the code is intended to break apart the string from the form into an int array.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Currently, when I type in numbers into the textbox and submit, the numbers disappear and nothing happens. Any help is greatly appreciated.
Your array variable is object. You have to split the value of <input type="text" id="array"> not the object element.
var array = document.getElementById("array");
array = array.value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Or simpler:
var array = document.getElementById("array").value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Change your code -
function findMaxSum() {
var array = document.getElementById("array").value.split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Problem is you are using button inside form, which is by default of type submit type, that is the reason why the page goes blank, it gets submitted. So either you don't use form tag or make the button as button type.
<button id="sum" type='button'>findMaxSum!</button> <!-- type attribute added -->
Below is the sample updated code, hope it helps you.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").value.split(/\s/);
var max = Math.max.apply(Math, array);
document.getElementById("answer").innerHTML = "The answer is: " + max;
}
window.onload = function() {
document.getElementById("sum").onclick = findMaxSum;
};
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p>Enter numbers with spaces, i.e. "1 2 3 4 5":</p>
<input type="text" id="array">
<br>
<button id="sum" type='button'>findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is:</p>
To achieve the solution of the problem, you need to make following changes.
Update the event binding place
window.onload = function() {
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
};
function findMaxSum() {
// remove the update binding code from here
// logic should come here
}
Resolve a JS error
document.getElementById("array").value.split(" ")
Update the html to avoid page refresh (add type)
<button id="sum" type='button'>findMaxSum!</button>
Update the logic to address the problem
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
var counter = i+1;
while (counter < array.length) {
var loopSum = array[i];
for (var j = (i+1); j <= counter; j++) {
loopSum += array[j];
if(loopSum > currentMax) {
currentMax = loopSum;
}
}
counter++;
}
}
Here is a plunker - http://plnkr.co/edit/AoPANUgKY5gbYYWUT1KJ?p=preview

Javascript: Detect checked boxes isn't working with form with only 1 checkbox. Working with 2 or more

I have the function below. It gets the values from checked boxes and transfer it to a textbox. It is working... but only if the form has 2 or more checkboxes.
<script type="text/javascript">
function sendValue()
{
var all_values = '';
boxes = document.DataRequest.itens.length
for (i = 0; i < boxes; i++)
{
if (document.DataRequest.itens[i].checked)
{
all_values = all_values + document.DataRequest.itens[i].value + ","
}
}
window.opener.document.getElementById('emailto').value = all_values;
self.close();
}
</script>
<form name="DataRequest">
<input name="itens" type="checkbox" value="name1">
<input name="itens" type="checkbox" value="name2">
</form>
Am I missing something to make this work with only 1 checkbox?
When there is one item. it does not return array
function sendValue()
{
var all_values = '';
boxes = document.DataRequest.itens.length
if(boxes>1)
{
for (i = 0; i < boxes; i++)
{
if (document.DataRequest.itens[i].checked)
{
all_values = all_values + document.DataRequest.itens[i].value + ","
}
}
}
else
{
if (document.DataRequest.itens.checked)
{
all_values = document.DataRequest.itens.value
}
}
window.opener.document.getElementById('emailto').value = all_values;
self.close();
}
First, you need to give different names to your inputs :
<form name="DataRequest">
<input name="item1" type="checkbox" value="name1">
<input name="item2" type="checkbox" value="name2">
</form>
Using the same name to your inputs is technically possible in your case but a terrible practice as the name is normally what's identify for a form the different inputs.
Then, to access your inputs, you must use a different syntax. More than one version are possible but you can do this :
var boxes = document.forms['DataRequest'].getElementsByTagName('input');
var tokens = [];
for (var i=0; i<boxes.length; i++) {
if (boxes[i].checked) tokens.push(boxes[i].name+'='+boxes[i].value);
}
var all_values = tokens.join(',');
Note that the use of join avoids the trailing comma.
not sure how much compatibility you need with IE 6 - 8, but if that's not required you can use
function serializeChecked() {
var values = [];
var checked_boxes = document.querySelectorAll('form[name="DataRequest"] input[checked]');
for (var i = 0, l = checked_boxes.length; i < l; i++) {
values.push(checked_boxes[i].getAtrribute('value'))
}
return values.join(',');
}
function sendValue() {
window.opener.document.getElementById('emailto').value = serializeChecked();
}
If you do require IE support, use document.DataRequest.getElementsByTagName('input') instead of QSA and iterate through them to collect the values if they have the checked attribute.

How to manipulate form field values in javascript

I'm trying to get the value of a few checkboxes and enter them in a hidden form field.
My checkboxes look like this:
<form>
<input type="checkbox" name="chicken" id="chicken" value="chicken"/>Chicken
<input type="checkbox" name="meat" id="meat" value="meat"/>Meat
</form>
<form method="post" action="">
<input type="hidden" name="my-item-name" value="" />
<input type="submit" name="my-add-button" value=" add " />
</form>
I only need to submit the hidden field data so I'd like the value of the hidden field change when the checkbox is ticked. So if the first checkbox is ticked I'd like the value of the hidden field to become chicken and if both of them are ticked the value should be chicken,meat.
I'm using the following javascript
function SetHiddenFieldValue()
{
var checks = document.getElementsByName("checkbox");
var hiddenFieldVal = "";
for(i = 0; i < checks.length; i++)
{
if(hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}
but when I add the items, it adds both of them, it doesn't check which one's been checked, is there a way to fix that, so when the first item is checked it'll only add that item and if both of them are checked, it'll add 2 items separated by comma,
for(i = 0; i < checks.length; i++)
{
if (!checks[i].checked)
continue;
....
}
You need to give the checkboxes the same name to have them grouped:
<input type="checkbox" name="food[]" id="chicken" value="chicken"/>Chicken
<input type="checkbox" name="food[]" id="meat" value="meat"/>Meat
And in your JavaScript function:
function SetHiddenFieldValue() {
var checks = document.getElementsByName("food[]");
var hiddenFieldVal = "";
for (var i=0; i<checks.length; i++) {
if (checks[i].checked) {
if (hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}
You forgot to test for checks[i].checked
function SetHiddenFieldValue() {
var checks = document.getElementsByName("checkbox");
var hiddenFieldVal = "";
for(i = 0; i < checks.length; i++) {
if (checks[i].checked) {
if(hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
}
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}
Hi your best to put the values into an array, makes it easier to then create the comma separated value. Also makes it a lot easier if you add more options later.
function SetHiddenFieldValue()
{
var checks = document.getElementsByName("checkbox");
var foods = new Array();
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
foods[i] = checks[i].value;
}
}
document.getElementById('my-item-name').value = foods.join(",");
}

Categories