only write predefined text in textbox using javascript - javascript

I want to do in textbox only add predefined text.
<input type="text" class="mytxt" onkeyup="return SplitChar(this.id);">
<script>
function SplitChar(txt) {
var mainval = document.getElementById(txt).value;
var Data = "hello".split('');
var Datas = mainval.split('');
var charLen = mainval;
if (Datas[mainval.length - 1] == Data[charLen.length - 1]) {
return true;
} else {
document.getElementById(txt).value = mainval.substr(0, mainval.length - 1);
alert("Please write as specified example");
return false;
}
}
</script>
in this text box only written "helloo" nothing else
i want to check on keyup event. and whith out use event function
Can anyone give me a suggestion?

Try this code.
Remove this.id in onkeyup="return SplitChar(this.id);" because you aready accessing in JS as var mainvaland add id to input because you accessing its value based on id
function SplitChar() {
var mainval = document.getElementById('txt').value;
var Data = "hello".split('');
var Datas = mainval.split('');
var charLen = mainval;
if (Datas[mainval.length - 1] == Data[charLen.length - 1]) {
return true;
} else {
document.getElementById('txt').value = mainval.substr(0, mainval.length - 1);
alert("Please write as specified example");
return false;
}
}
<input type="text" class="mytxt" id="txt" onkeyup="return SplitChar();">

Related

The sum cannot show although i click on the button

What I want is, after the user enters the number of subjects, the system will show the number of input box according to the number of subjects entered, then when the user clicks on the button, it should show the sum. I tried many ways, but I failed to show the sum, anyone knows what is the mistake I made?
Below is my code:
function select() {
var x = parseInt(document.getElementById('1').value);
if (document.getElementById('1').value == "") {
alert("Please fill up number of subject");
} else if (isNaN(x) == true) {
alert("Please fill up number of subject with number");
} else {
var subject = parseInt(document.getElementById('1').value);
var sum = 0;
for (var num = 1; num <= subject; num++) {
document.write("Enter the mark for subject " + num + " : ");
var value = parseFloat(document.write("<input/><br>"));
sum += value;
}
var calc = document.write("<button>Next</button><br>");
calc.onclick = function() {
next()
};
function next() {
document.write("Total marks: " + sum + "%");
}
}
}
<html>
<body>
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</body>
</html>
That's how I have rewritten a big part of your code. I have place inline comments to explain what I do.
function select() {
var x = parseInt(document.getElementById('1').value, 10);
// Getting the div that wraps the initial form.
var formWrapper = document.querySelector('.formWrapper');
// Getting the div, that is going to display the new fields and the results.
var results = document.querySelector('.results');
// I have switch your statement from x == '' to '' === x as it
// consists a good practice
if ( '' === x ) {
alert("Please fill up number of subject");
// I have remove the isNaN(x) == true, because the isNan will
// be either true or false.
} else if ( isNaN(x) ) {
alert("Please fill up number of subject with number");
} else {
// Using parseInt(x, 10) to set the base.
var subject = parseInt(x, 10);
// In this array, I store the auto-generated fields.
var fieldsList = [];
// Removing the first div from the DOM
formWrapper.parentElement.removeChild(formWrapper);
for ( var num = 1; num <= subject; num++ ) {
// I am creating a new field
var newField = document.createElement('input');
// I push the field into the array I made for the fields.
fieldsList.push(newField);
// I append the field in the HTML
results.appendChild(newField);
// I create a <br> tag
var br = document.createElement('br');
// And I append the tag in the DOM
results.appendChild(br);
}
// I create the button that is going to handle the Next functionality
var nextButton = document.createElement('button');
// I set the button text
nextButton.innerText = 'Next';
// I add an Event Listener for the click event.
nextButton.addEventListener(
'click',
function() {
// I reset the sum to 0
var sum = 0;
// I itterate the fields auto-generated and saved in the array
fieldsList.forEach(
function(field) {
// I get the value
sum += parseInt(field.value, 10);
}
);
// I create the field that is going to display the output
let resultText = document.createElement('div');
// I set the text based on the sum
resultText.innerText = "Total marks: " + sum + "%";
// I append the text message to the DOM
results.appendChild(resultText);
}
);
// I append the button to the DOM
results.appendChild(nextButton);
}
}
<html>
<body>
<div class="formWrapper">
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</div>
<div class="results"></div>
</body>
</html>

How to allow one specific word into text field in form using javascript?

I have input number field which is from 1000 to 10000 range but I also want to allow one only word 'All' into this field if user enter any word then show error. I have not written any JavaScript code for this because I do not have any idea how to do this. can anyone help me out please? Thanks
<input type="text" class="form-control" id="validationCustom02" min="1000" max="10000" required>
Here is my javascript solution: It uses a single If statement to check if the string is a number or ALL. Technically you don't need the isNaN function in there so if you want to remove it, the if statement will still work.
var _input = document.querySelector(".validate-num");
var _min= 1000;
var _max = 10000;
_input.addEventListener("input",function(){
var _valid = ((isNaN(this.value) && this.value.toLowerCase() == "all") || (!isNaN(this.value) && (this.value >= _min && this.value <= _max)));
if(!_valid){
var error = document.getElementById("error");
error.innerHTML = "Value Must be 1000 to 10000 or ALL";
}
});
<input type="text" class="validate-num form-control" id="validationCustom02" required>
A number type can't have strings into it, you will have to have a text input with an Event listener which does the validation job For You. Here, I have added a blur listener, it would trigger once you move away from the input.
const inputElem = document.querySelector('#validationCustom02required');
inputElem.addEventListener('blur', (e) => {
const val = e.target.value;
let showError = false;
if (isNaN(val)) {
if (val.toLowerCase() !== 'all') {
showError = true;
}
} else {
const numVal = +val;
if (val < 1000 || val > 10000) {
showError = true;
}
}
const errorElem = document.querySelector('#error');
if (showError) {
errorElem.innerText = 'Invalid; Value!';
} else {
errorElem.innerText = '';
}
})
<input type="text" class="form-control" id="validationCustom02required">
<div id="error"></div>

Add user input to array // Javascript

This is the code I have so far. When the user enters a word into the input box, I want that word to be stored in an array via the Add Word button. Once a number of words have been entered, the user clicks the Process Word button and I want all the words in the array to appear. How would I do this? Also could someone also explain why when nothing is entered into the input box "field is empty" does not appear?
function begin() {
var word = "List of words";
var i = returnword.length
if (userinput.length === 0) {
word = "Field is empty"
}
document.getElementById('message2').innerHTML = word
while (i--) {
document.getElementById('message').innerHTML = returnword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
var arrword = [];
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
Addword()
Your function contains an array arrword. If you keep it inside your function it will be reset every time you call the function. You need to keep your array of words outside the function
Empty input
The empty input message should be shown when you click on the Add word button. Check the input and display a message if needed
Display word
You can simply use join() to display you array
var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');
function addWord() {
errorElement.innerHTML = "";
var word = inputElement.value;
if (word.trim() === "")
errorElement.innerHTML = "Empty input";
else
arrayOfWord.push(word);
inputElement.value = "";
}
function process(){
words.innerHTML = arrayOfWord.join(' - ');
}
#error {
color: tomato;
}
#words {
color: purple;
}
Enter a word <input id="userinput" /><button onclick="addWord()">Add word</button>
<div id="error"></div>
<button onclick="process()">Process</button>
<div id="words"></div>
you can do something a bit clearer with jQuery! :)
if you handle the input with jquery you can write something like:
var arrWord = [] // your array
/* Attaching a click handler on your "Add Word" button that will
execute the function on user click */
$("#addWordButtonID").on("click", function () {
var wordTyped = $('#textInputID').val() // your var that collect userInput
if (wordTyped.length != 0) { // your if statement with length === 0 condition
arrWord.push(wordTyped) // adding word typed to the array
}
})
to add jquery to your html page, just add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
in your html header
Hopefully you already have the right html. Then you can modify your script like below:
<script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
</script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
<button id="addWord" onclick="addword()">Add Word</button>
<button id="processWords" onclick="begin()">ProcessWords</button>
<input type="text" id="userinput" value=" " />
<div id="message2">
</div>
<div id="message">
</div>

textbox calculator with parsing function to arithmetic function

What I'm trying to do is have 2 text boxes that connect to one button. When the button is clicked, it calls a function to parse the 2 text box entries and then perform an addition (2 seperate functions). Can anybody point out what I'm missing on this? I keep getting num1 as undefined when I call it in the console.
<!DOCTYPE html>
<html>
<head>
<title>.</title>
</head>
<body>
Number1: <input type='text' id='num1'><br>
Number2: <input type='text' id='num2'><br>
<br>
<button onclick='add()'>Add</button>
<div id='toUser'></div>
<script>
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
function parsing()
{
var num1mod = parseFloat($('n1')).value;
var num2mod = parseFloat($('n2')).value;
if (isNaN(num1mod || num2mod))
{
user.innerHTML = ('Please enter a valid number');
}
else
{
add();
}
}
function add()
{
parsing();
return num1mod + num2mod;
user.innerHTML = (return)
}
</script>
</body>
</html>
Try this,
function parsing()
{
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
var num1mod = parseFloat(n1);
var num2mod = parseFloat(n2);
if (!isNaN(n1) || !isNaN(n2))
{
user.innerHTML = 'Please enter a valid number';
}else{
var total = num1mod + num2mod;
user.innerHTML = total;
}
return false;
}
There are a few problems with this code:
$('num1') appears to be jQuery or some other library. From the tags though it doesn't look like you are using jQuery.
If you are using jQuery, $('num1') is an invalid selector. It should be $('#num1')
If you are using jQuery, it should be .val() rather than .value and it should be inside the preceding parenthesis ($('#num1').val()), not outside.
Native JavaScript:
var num1mod = parseFloat(n1, 10);
var num2mod = parseFloat(n2, 10);
jQuery:
var num1mod = parseFloat($('#num1').val(), 10);
var num2mod = parseFloat($('#num2').val(), 10);

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources