Control an input which filled automatically by a script - javascript

I have this script which checking if the value of variable is match or not value of a hidden input and return a confirmMessage.
the value of var maybe filled manually or automatically by another script.
when its manually there is a result, but when the input is filled automatically with a script i got no confirmmessage.
<script>
$('#vr').on('keyup change', function() {
var vr = document.getElementById('vr');
var confirm_vr = document.getElementById('confirm_vr');
var message = document.getElementById('confirmMessage');
if(vr.value == confirm_vr.value){
message.innerHTML = "MATCH";
}else{
message.innerHTML = "! Not match";
}
});
</script>
<span id='confirmMessage' ></span>
<input id='vr' name='vr' />
<input type='hidden' id='confirm_vr' name='confirm_vr' />

How do you set the input value "automatically with a script"? just by document.getElementById('vr').value = 'hello'? As easiest solution I would suggest to extract your handler logic into the global function and call it when you change the input via code:
<script>
function processChange() {
var vr = document.getElementById('vr');
var confirm_vr = document.getElementById('confirm_vr');
var message = document.getElementById('confirmMessage');
if(vr.value == confirm_vr.value){
message.innerHTML = "MATCH";
}else{
message.innerHTML = "! Not match";
}
};
$(function() {
$('#vr').on('keyup change', processChange);
});
</script>
<span id='confirmMessage' ></span>
<input id='vr' name='vr' />
<input type='hidden' id='confirm_vr' name='confirm_vr' />
<script>
$(function() {
document.getElementById('vr').value = 'hello';
processChange();
});
</script>

Adding another answer because #dhilt's answer requires that you change the code that sets the input value everytime you add a new listener.
$('#vr').on('keyup change', function() {
var vr = document.getElementById('vr');
var confirm_vr = document.getElementById('confirm_vr');
var message = document.getElementById('confirmMessage');
if(vr.value == confirm_vr.value){
message.innerHTML = "MATCH";
}else{
message.innerHTML = "! Not match";
}
});
$('#vr').on('keyup change', (e) => {
// This will get called without the code that sets
// input.value having to know about this handler
console.log('Value changed', e);
});
$('button').on('click', function() {
var vr = document.getElementById('vr');
vr.value += 'X';
// Notice that you don't need to know what handlers are set
$(vr).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id ="vr"/>
<span id='confirmMessage' ></span>
<input id='vr' name='vr'>
<input type='hidden' id='confirm_vr' name='confirm_vr' value="X"/>
<hr />
<button>Set text value</button>

Related

JavaScript function/event listener not functioning properly

I'm completely new to JavaScript, and don't know why this isn't working. When I click on the input box, and type in less than 5 characters, i want a message to display. The message is simply not showing. Source code: https://jsfiddle.net/015por64/
<html>
<body>
<form id="form>">
<input id="input">
<div id="text"> Test </div>
</input>
</form>
</body>
</html>
<script>
function checkUserName(e, minLength) {
var username = document.getElementById("input");
var usernameLength = username.textContent;
if (usernameLength.value.length < 5) {
msg = "Your username must consist of at least five characters."
};
else {
msg = "";
text.innerHTML=msg
};
}
var text = document.getElementById("text");
text.addEventListener("blur", function(e) {checkUserName(e, 5)}, false)
</script>
Few issues with your code:
you need to attach the event to #input and not the div#text.
you need to read value of #input and not textcontent
; after if is wrong because then else will give syntax error.
<html>
<body>
<form id="form>">
<input id="input">
<div id="text"> Test </div>
</input>
</form>
</body>
</html>
<script>
function checkUserName(e, minLength) {
var username = document.getElementById("input");
var usernameLength = username.value;
if (usernameLength.length < 5) {
msg = "Your username must consist of at least five characters.";
text.innerHTML=msg;
}else {
msg = "";
text.innerHTML=msg;
};
}
var text = document.getElementById("text");
document.getElementById('input').addEventListener("blur", function(e) {checkUserName(e, 5);}, false)
</script>
It should be the input where you have to put the blur event listener.
var input = document.getElementById("input");
And since you have no use for text outside the function, better define it inside.

javascript - Confirm/Cancel before onclick button function

I have a button that submits a payment for my website using a function that's defined in an external file. I want to add in an alert box popup for confirming or cancelling the function that's called with the button's onclick. I'm familiar with javascript, however, I'm not sure of how exactly to call the function within another if it's defined externally.
What I have:
<script type="text/javascript">
var $jj = jQuery.noConflict();
$jj(document).ready(function () {
$jj('.alertbox').on('click', function () {
var _this = $jj(this);
$jj.confirm({
title: 'Confirm!',
content: 'Are you sure?',
buttons: {
confirm: function review.save(); {
},
cancel: function () {
}
}
});
});
});
</script>
Button phtml:
<button type="submit" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Place Order')) ?>" class="button btn-checkout alertbox" onclick="review.save();" ><span><span><?php echo $this->__('Place Order') ?></span></span></button>
I know this does not work, as I get the following error:
Uncaught ReferenceError: review is not defined
at HTMLButtonElement.onclick
Do I get rid of the onclick?
Is there a more efficient way of doing this? Maybe using a form and input rather than button?
$('#press').on('click', function(){
var val = validate();
if(val == true){
var r = confirm("Submit form!")
var txt;
if (r == true) {
txt = "You pressed OK!";
//$( "#myform" ).submit(); //use this for submitting the form
} else {
txt = "You pressed Cancel!";
}
alert(txt); //this line of code for test reasons
}
else{
alert("input fields empty");
}
});
function validate(){
var val = true;
var teste1 = $("#input1").val();
var teste2 = $("#input2").val();
if(teste1== "" || teste1 == null){
var val = false;
//some css and jquery to change the input color
}
if(teste2 == "" || teste2 == null){
var val = false;
//some css and jquery to change the input color
}
return val;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id = "myform" action="test.php" method="post">
<input type = "text" id ="input1" value = "">
<input type = "text" id ="input2" value = "">
<button id = "press" type="button">Click Me!</button>
</form>

Detect text filled by barcode scanner(reader) javascript

The code checks barcodes using a barcode scanner.
Search_code is filled by a user (keyboard) , and insert_code is filled automatically by a barcode scanner.
Currently, code works if both inputs are introduced in barcode scanner values ​​which is not functional for me.
The code needs to run when:
search_code is entered manually ( keyboard ) and
insert_code is filled automatically by the barcode scanner
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate(e) {
e.preventDefault();
// show verification result:
if (search_code.value == insert_code.value) {
result.textContent = 'code ok';
result.className = "ok";
audio.play();
} else {
result.textContent = 'code is not ok';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
function clearField(input) {
input.value = "";
};
....
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value=""/><br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>
</div>
<div id="result"></div>
</div>
<script src="js/action_input.js"></script>
</body>
</html>
Thank you!
To prevent a textbox from being filled by a bar-code reader simply disable onpaste event .
$(document).ready(function(){
$('#search_code').bind("cut copy paste",function(e) {
e.preventDefault();
});
});

Get input from textbox and write it below

I need to take the value from an input box and write it below the input box on the click of a button. I thought to use a label but if there is another way I am open to suggestions.
My code so far:
<h1>Test</h1>
<form name="greeting">
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
<script lang="javascript">
function getName() {
var inputVal = document.getElementById("name").value;
if (inputVal == "") {
document.getElementById("name").style.backgroundColor = "red";
}
else {
document.write("Hello " + document.getElementById("name"));
}
First of all, you don't want to submit a form, so change button type from "submit" (default) to "button".
Then you should not use document.write almost never, it's used in very specific cases. Use proper DOM manipulation methods like appendChild. I would use convenient insertAdjacentHTML:
function getName() {
var input = document.getElementById("name");
if (input.value == "") {
input.style.backgroundColor = "red";
} else {
input.insertAdjacentHTML('afterend', '<div>' + input.value + '</div>');
}
}
<form name="greeting">Type your name here:
<input type="Text" name="fullname" id="name" />
<button type="button" onclick="getName()">Create</button>
<br>Hello
<label id="greet">Hello</label>
</form>
First you need to stop your form from submitting. Second you should not use document.write, since it will not append the text as wanted after the input field. And last you need to validate the elements value and not the element itself.
<html>
<head>
<script>
//First put the function in the head.
function getName(){
var input = document.getElementById("name");
input.style.backgroundColor = ''; //Reseting the backgroundcolor
if (input.value == ''){ //Add the.value
input.style.backgroundColor = 'red';
}
else{
//document.write('Hello ' + input.value); //This would overwrite the whole document, removing your dom.
//Instead we write it in your greeting field.
var tE = document.getElementById('greet');
tE.innerHTML = input.value;
}
return false //Prevent the form from being submitted.
}
</script>
</head>
<body>
<h1>Test</h1>
<form name = 'greeting'>
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="return getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
</body>
</html>
You need to cancel the submit event which makes the form submit, alternatively you could not wrap everything inside a form element and just use normal div that way submit button wont submit.
Demo : https://jsfiddle.net/bypr0z5a/
Note reason i attach event handler in javascript and note onclick attribute on button element is because jsfiddle works weird, on ordinary page your way of calling getName() would have worked.
byId('subBtn').onclick = function (e) {
e.preventDefault();
var i = byId('name'),
inputVal = i.value;
if (inputVal == "") {
i.style.backgroundColor = "red";
} else {
byId('greet').innerText = inputVal;
i.style.backgroundColor = "#fff";
}
}
function byId(x) {
return document.getElementById(x);
}

How to alert user for blank form fields?

I have this form that has 3 inputs and when a user leaves a field blank a dialogue box pops up to alert the user a field is blank. The code I have below only works for 2 specific input. When i try adding another input to the code it doesnt work. It only works for 2 inputs. How can I make it work for all three?
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Your Google Map's mileage\n";
}
if(location=='' )
{
missingFields = true;
strFields += " Your business name\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>
Showing 3 alerts may be disturbing, use something like this:
$(document).on('submit', 'form', function () {
var empty = $(this).find('input[type=text]').filter(function() {
return $.trim(this.value) === "";
});
if(empty.length) {
alert('Please fill in all the fields');
return false;
}
});
Inspired by this post.
Or you can do validation for each field this way using HTML data attributes:
<form data-alert="You must provide:" action="" method="post">
<input type="text" id="one" data-alert="Your Google Map's mileage" />
<input type="text" id="two" data-alert="Your business name" />
<input type="submit" value="Submit" />
</form>
... combined with jQuery:
$('form').on('submit', function () {
var thisForm = $(this);
var thisAlert = thisForm.data('alert');
var canSubmit = true;
thisForm.find('input[type=text]').each(function(i) {
var thisInput = $(this);
if ( !$.trim(thisInput.val()) ) {
thisAlert += '\n' + thisInput.data('alert');
canSubmit = false;
};
});
if( !canSubmit ) {
alert( thisAlert );
return false;
}
});
Take a look at this script in action.
Of course, you can select/check only input elements that have attribute data-alert (which means they are required). Example with mixed input elements.
You can add the required tag in the input fields. No jQuery needed.
<input required type="text" name="name"/>
Try this
var fields = ["a", "b", "c"]; // "a" is your "mile"
var empties= [];
for(var i=0; i<fields.length; i++)
{
if(!$('#'+fields[i]).val().trim())
empties.push(fields[i]);
}
if(empties.length)
{
alert('you must enter the following fields '+empties.join(', '));
return false;
}
else
return true;
instead of this
var name = $('#mile').val();
if (!name.trim()) {
alert('you must enter in your mile');
return false;
}

Categories

Resources