Javascript function to show text if i input value - javascript

To the point, if i input value "20" in input field then show message "Thank you".
Here's my HTML Code:
<form method="post" action="">
<input type="text" id="nominal" value="">
<input type="submit" value="submit">
</form>
Here's my JS Code:
$(document).ready(function(){
var money = 20;
/* not sure if this is written correctly, but this is supposed to
check whether the hidden input element value is equal to var money */
if ($("input[id='nominal']").val() == money ) {
var h = document.createElement("H1") // Create a <h1> element
var t = document.createTextNode("Thank You"); // Create a text node
h.appendChild(t); // Append the text to <h1>
};
});
i've created one script to fulfill what I need, but not working! what's wrong?
My JDFIDDLE LINK

You have to create an event to listening for changes, in this case changed. And you can make your code a bit smaller too. ;)
$(function() {
$("#nominal").change(function() {
if( $(this).val() == 20 )
$(this).after("<h1>Thank You</h1>");
});
});
Full working exaple with removing the message when value changes again and strict check can be seen here.

$(document).ready(function(){
var money = 20;
$("#nominal").change(function() { // take change event of input box
if ($(this).val() == money ) { // use $(this) to take value
var h = document.createElement("H1"); // Create a <h1> element
var t = document.createTextNode("Thank You"); // Create a text node
h.appendChild(t);
$('form').append(h); // append created h1 element in form/html
} else {
$('form').find("h1").remove();
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form method="post" action="">
<input type="text" id="nominal" value="">
<input type="button" value="submit" name="submit" id="submit">
</form>

Related

HTML Form input into Javascript array

My goal is to enter a single name into a html Text form. Each time I press submit
it will store that value into a javascript array. Currently, I am able to get
the first value I submit into the array but not the subsequent values. Hope I am
being clear enough, Any help would be great.
Here is my JavaScript
function getListOfNames() {
"use strict";
//Declare variables
var form;
var getNameValue;
var myArray = [];
var output;
//Assign values
output = document.getElementById("myTable");
form = document.getElementById("myForm");
getNameValue = form.getNameValue.value;
//Each time form is submited put the new value into array
myArray.push(getNameValue);
//output the results
output.innerHTML = myArray;
}
function project5Part2() {
"use strict";
// Your code goes in here.
getListOfNames();
return false;
}
Here is my HTML
<form id="myForm" action="#" onsubmit=" return project5Part2();" >
<label for="firstName">Enter Name</label>
<input type="text" id="enteredName" name="getNameValue"/>
<input type="submit" value="Enter Name" />
<input type="reset"  value="Clear form - DO NOT SEND" />
</form>
Remove the onsubmit from the form.
change the input type="submit" into a regular button and use the onclick to execute JavaScript.
<form id="myForm" action="#" >
<label for="firstName">Enter Name</label>
<input type="text" id="enteredName" name="getNameValue"/>
<button type="button" onclick="project5Part2();">Enter Name</button>
<input type="reset" value="Clear form - DO NOT SEND" />
</form>
Create or use a global array (cannot be enclosed in the method if you want to persist)
When the button is clicked, checked the value of the textbox and if not empty, add the value to the array.
var myArray = new Array();
function project5Part2() {
var name = document.getElementById('enteredName').value;
if (!(typeof name === 'undefined') && name!=null && name.trim()!='') {
myArray.push(name);
}
console.log(myArray);
document.getElementById('enteredName').value = '';
}
Will log the contents of the array each time the button is clicked.
For example: ["albert", "manny", "susan"]
The textbox value is being cleared each time the name is added.

enable buttons in javascript/jquery based on regex match

I'm having trouble getting the match to bind to the oninput property of my text input. Basically I want my submit button to be enabled only when the regular expression is matched. If the regex isn't matched, a message should be displayed when the cursor is over the submit button. As it stands, typing abc doesn't enable the submit button as I want it to. Can anyone tell me what I'm doing wrong? Thank you.
<div id="message">
</div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt = $("#txt").value();
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
// disable buttons with custom jquery function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
this.disabled = state;
});
}
});
$('input[type="submit"]).disable(true);
var match = function(){
if (txt.match(PATTERN)){
$("#enter").disable(false)
}
else if ($("#enter").hover()){
function(){
$("#message").text(REQUIREMENTS);
}
}
</script>
Your code would be rewrite using plain/vanille JavaScript.
So your code is more clean and better performance:
<div id="message"></div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = false;
} else if (isHover(enter)) {
enter.disabled = true;
message.innerHTML = REQUIREMENTS;
} else {
enter.disabled = true;
}
}
function isHover(e) {
return (e.parentElement.querySelector(':hover') === e);
}
</script>
If you wanted to say that you want handle the events in different moments, your code should be the following.
Note: the buttons when are disabled doesn't fired events so, the solution is wrapper in a div element which fired the events. Your code JavaScript is more simple, although the code HTML is a bit more dirty.
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<div style="display: inline-block; position: relative">
<input type="submit" id="enter" value="enter" disabled />
<div id="buttonMouseCatcher" onmouseover="showText(true)" onmouseout="showText(false)" style="position:absolute; z-index: 1;
top: 0px; bottom: 0px; left: 0px; right: 0px;">
</div>
</div>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = '';
} else {
enter.disabled = true;
}
}
function showText(option) {
message.innerHTML = option ? REQUIREMENTS : "";
}
</script>
Two problems here:
The variable txt is defined once outside the function match, so the value is fixed to whatever the input with id txt has when the script/page is loaded.
You should move var txt = $("#txt").val(); into the match function.
Notice I changed the function value() to val().
Problems identified:
jQuery events don't happen on disabled inputs: see Event on a disabled input
I can't fix jQuery, but I can simulate a disabled button without it actually being disabled. There's other hacks you could do to get around this as well, for example, by overlaying a transparent element which actually captures the hover event while the button is disabled.
Various syntactical errors: format your code and read the console messages
.hover()){ function() { ... } } is invalid. It should be .hover(function() { ... })
else doesn't need to be followed by an if if there's no condition
.hover( handlerIn, handlerOut ) actually takes 2 arguments, each of type Function
$('input[type="submit"]) is missing a close '
Problems identified by #Will
The jQuery function to get the value of selected input elements is val()
val() should be called each time since you want the latest updated value, not the value when the page first loaded
Design issues
You don't revalidate once you enable input. If I enter "abc" and then delete the "c", the submit button stays enabled
You never hide the help message after you're done hovering. It just stays there since you set the text but never remove it.
https://jsfiddle.net/Lh4r1qhv/12/
<div id="message" style="visibility: hidden;">valid entries must contain the string 'abc'</div>
<form method="POST">
<input type="text" id="txt" />
<input type="submit" id="enter" value="enter" style="color: grey;" />
</form>
<script>
var PATTERN = /abc/;
$("#enter").hover(
function() {
$("#message").css('visibility', $("#txt").val().match(PATTERN) ? 'hidden' : 'visible');
},
$.prototype.css.bind($("#message"), 'visibility', 'hidden')
);
$('form').submit(function() {
return !!$("#txt").val().match(PATTERN);
});
$('#txt').on('input', function() {
$("#enter").css('color', $("#txt").val().match(PATTERN) ? 'black' : 'grey');
});
</script>

How to make a word a link if the user has input # before it?

I am using this code:
<form oninput="x.value=a.value">Account Info <br>
<input type="text" id="a">First Name<br>
UserName <output name="x" for="a"></output>
</form>
I want i such a way that if the user inputs a word and he has place # before the word without space then how to make the word as a link. Means the tag which happens in facebook. Can it be done with java script and how.
This was just the example to demonstrate i want to intergrate this type in my project as comments. And it will be with php.
Thanks
Here's one example to check. It works with enter keypress and even prevents for adding same tags over again: http://codepen.io/zvona/pen/KpaaMN
<input class='input' type="text" />
<output class='output'></output>
and:
'use strict';
var input = document.querySelector('.input');
var output = document.querySelector('.output');
input.addEventListener('keyup', function(evt) {
if (evt.keyCode !== 13 || !input.value.length || ~output.textContent.indexOf(input.value)) {
return;
}
var tag = document.createElement('a');
tag.appendChild(document.createTextNode(input.value));
if (input.value.startsWith("#")) {
tag.setAttribute("href", input.value);
}
output.appendChild(tag);
input.value = "";
}, false);
<form>Account Info <br>
<input type="text" id="a">First Name<br/>
<output id="result" name="x" for="a"></output>
<button type="button" onclick="changeVal(document.getElementById('a').value)">Click</button>
</form>
<script>
function changeVal(value1){
var dt = value1.split(" ");
document.getElementById("result").innerHTML = "";
for(var t=0; t < dt.length; t++){
if(dt[t].startsWith("#")){
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" <a href='#'>"+dt[t]+"</a>";
}
else{
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" "+dt[t];
}
}
}
</script>
Checkout Jsfiddle demo
https://jsfiddle.net/tum32675/1/
You could use a textarea to input and a render to show the output. Then hiding the input and showing the output only. But that's another
story.
If you use a contentEditable div, you can actually insert and render the html from it in the same component. Check it out!
$(document).on("keyup","#render", function(){
var words = $(this).text().split(" ");
console.log(words);
if (words){
var newText = words.map(function(word){
if (word.indexOf("#") == 0) {
//Starts with #
//Make a link
return $("<div/>").append($("<a/>").attr("href", "#").text(word)).html();
}
return word;
});
}
$(this).empty().append(newText.join(" "));
placeCaretAtEnd( $(this)[0]);
});
Here is the Plunker
Thanks for the attention.

Update bg colour of text input in html form via javascript

I have a form that I want to validate before the user is able to submit it. To do this I have written a basic js file that checks a value is not left blank. In the event that this is the case I want the background colour of the text field to update to be red. I have looked around online and am struggling to get this working. Here is what I have so far:
HTML Form:
<script language="javascript" src="validateForm.js"></script>
<form name="contact form">
<input type="text" name="name"></td>
<input type="button" value="Send" onsubmit="return validateForm()" method="post">
</form>
Javascript:
function validateForm()
{
var result = true;
var form = document.forms["contact form"];
// Name
var name = form["name"].value;
if ( name == null || name == "" )
{
form["name"].style.backgroundColor = red;
result = false;
}
return result;
}
Please could someone help me get this working?
Use red as string ( you missed the quote) jsfiddle
form["name"].style.backgroundColor = "red"; // not red

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources