Save text field to a variable using jQuery, showing undefined - javascript

I am trying to save the text field with the id #modelBox to a global variable so that it can be used later. However it seems no matter what I try the modelNumber is alerting 'undefined'. Any help is appreciated.
<input type = "textbox" value = "Enter Model Number" id="modelBox">
var modelBox="";
$('#modelBox').val('test');
var modelNumber = $('#modelBox').val();
alert(modelNumber);
var manufacturer = "unknown";
$(document).ready(function(){
$('#submit').click(function findManufacturer(){
var firstFour = modelNumber.substring(0,4);
if (firstFour.includes("B")){
manufacturer = "AU Optronics";
$('#answer').after("AU Optronics");
}else{
$('#answer').after("No Manufacturer found");
}
});
});

this needs to be INSIDE your click handler so that you grab the value when you click. The way you have it, the val gets set on page load -- which is likely undefined at that point.
var modelNumber = $('#modelBox').val();
$('#submit').click(function findManufacturer(){
var modelNumber = $('#modelBox').val();
var firstFour = modelNumber.substring(0,4);
if (firstFour.includes("B")){
manufacturer = "AU Optronics";
$('#answer').after("AU Optronics");
}else{
$('#answer').after("No Manufacturer found");
}
});
});
EDIT: You can also place it outside of the click handler, so long as it is inside the docready, and the field never changes between page load and clicking the submit button.

I just tried your code in below snippet, it alerts 'test'. Found no issue!
var modelBox = "";
$('#modelBox').val('test');
var modelNumber = $('#modelBox').val();
alert(modelNumber);
var manufacturer = "unknown";
$(document).ready(function() {
$('#submit').click(function findManufacturer() {
var firstFour = modelNumber.substring(0, 4);
if (firstFour.includes("B")) {
manufacturer = "AU Optronics";
$('#answer').after("AU Optronics");
} else {
$('#answer').after("No Manufacturer found");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="textbox" value="Enter Model Number" id="modelBox">

Related

how to call an alert after an option is clicked

I am trying to make a username, ID and password linking form but i need to make sure that the program recognises that a username has been selected.
This is what I have done:
var usernameBox = document.getElementsByName("uop");
usernameBox.onclick = function(){
if (usernameBox.options[usernameBox.selectedIndex].value == false){
alert("Please choose your username");
}
}
This does not work for me and I am a beginner to javascript so I'm not very familiar with a lot of the concepts but that's what learning is for right.
You could add the onchange attribute in the HTML itself, which calls a function in the JavaScript.
Heres a example
<input type="text" onchange="inputOnChange()" id="input-username"/>
<script>
function inputOnChange() {
let usernameinput = document.getElementById("input-username");
let username = usernameinput.value;
// do whatever u want with the username now
console.log(username);
}
</script>
You could update a variable everytime the 'select' element is changed, then show the alert. You can use the username variable wherever you would like. Here is how you could do this...
var usernameBox = document.getElementById("uop");
let username = usernameBox.value;
usernameBox.onchange = (e) => {
username = e.target.value;
alert(username);
}

php and javascript form validation issue

I have created a form using bootstrap and am using javascript for form validation and then a php script to grab the post data and display it
the basic structure is the following and I have made this as minimal as I could to address this specific issue. The issue I am having is that the script to check for the form validation works perfectly in the <script> tags at the end of the body, but instead of preventing the page from being submitted as it should it still processes to the next page with the form's contents that are being made through the php post action when the form is indeed not filled out correctly.
Why is this? Should the form validation still not stop the page from moving on to the post data since the validation is returning false if the form has not been submitted correctly. All the form validation alerts pop up correctly and I;m getting no console errors after checking, or do I need to perform an additional check to only process the post data if the form is valid?
<html>
other tags.....
<body>
<form name = "OrderForm" action = "process_order.php" onsubmit = "orderbutton" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
</body>
<script>
function CheckForm() {
var Name = document.getElementById("Name");
var fries = document.forms.OrderForm.FryRadio;
var fryyes = fries[0].checked
var fryno = fries[1].checked
var bool = true;
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked))) {
bool = false;
}
else if (!(fryyes || fryno)) {
bool = false;
}
if (!(bool)) {
alert("Please fill out all of the required fields.");
return false;
}
else {
alert("Your order is being submitted");
console.log("Submitted")
}
};
</script>
</html>
You should call function on submit , I dont know what are you doing with current onsubmit='...'
So use following, call function when you submit the form.
<form name = "OrderForm" action = "process_order.php" onsubmit = "return CheckForm()" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
For demo : Check Fiddle
first of all what you can do is:
you do not need the !fryes in another if statement:
you can do it also in the first if:
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked)) || ( (!(fryyes || fryno))) {
bool = false;
}
also what you can do is if bool is false, disable your submit button if there is any?
you can also do an onchange on the texboxes, that way you can validate each text box or checkbox one by one. and have the bool true and false?
I did something like this on jquery long time ago, for validation, where I checked each texbox or dropdown against database and then validate, aswell..
The code is below
<script>
$(document).ready(function(){
var works=true;
//Coding for the captcha, to see if the user has typed the correct text
$('#mycaptcha').on('keyup',function(){
if($('#mycaptcha').val().length>=5){
$.post("user_test/captcha_check.php",
{
// userid: $("#userlogin").val(),
mocaptcha: $("#mycaptcha").val(),
},
function(data,status){
if(data==0){
document.getElementById("final_error").innerHTML="Captcha did not match";
works=false;
}
if(data==1){
works=true;
document.getElementById("final_error").innerHTML="";
}
});
}
});
//Works like a flag, if any mistake in the form it will turn to false
//Coding the submit button...
$('#submitbtn').on('click',function(){
var arrLang = [];
var arrPrf = [];
uid = $("#userid").val();
capc = $('#mycaptcha').val();
pwd = $("#pwd1").val();
fname = $("#fname").val();
lname = $("#lname").val();
email = $("#memail").val();
pass = $("#pwd2, #pwd1").val();
daysel = $('#dayselect').val();
monthsel = $('#monthselect').val();
yearsel = $('#yearselect').val();
agree_term = $('#agree_box').prop('checked');
//checks if the textboxes are empty it will change the flag to false;
if((!uid) || (!capc) ||(!fname) || (!lname) || (!email) || (!pass) || (!daysel) || (!monthsel) || (!yearsel) || (!agree_term)){
works=false;
}
if(!works){
document.getElementById('final_error').innerHTML ="<font size='1.3px' color='red'>Please fill the form, accept the agreement and re-submit your form</font>";
}
else{
works=true;
//A jquery function, that goes through the array of selects and then adds them to the array called arrLang
$('[id=lang]').each(function (i, item) {
var lang = $(item).val();
arrLang.push(lang);
});
//A jquery function, that goes through the array of select prof and then adds them to the array called arrprf
$('[id=prof]').each(function (i, item) {
var prof = $(item).val();
arrPrf.push(prof);
});
var data0 = {fname: fname, mlname : lname, userid : uid,password:pwd, emailid : email, mylanguage : arrLang, proficient : arrPrf, dob : yearsel+"-"+monthsel+"-"+daysel};
//var json = JSON2.stringify(data0 );
$.post("Register_action.php",
{
// userid: $("#userlogin").val(),
json: data0,
},
function(data,status){
if(data==1){
//alert(data);
window.location = 'Registered.php';
}
document.getElementById("userid_error").innerHTML=data;
});
}
});
//to open the agreement in a seperate page to read it..
$("#load_agreement").click(function () {
window.open("agreement.html", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
});
//A code that loads, another page inside the agreement div
$( "#agreement" ).load( "agreement.html" );
//This part here will keep generating, duplicate of the language and profeciency box, incase someone needs it
$('#Add').click(function(){
//we select the box clone it and insert it after the box
$('#lang').clone().insertAfter("#lang").before('<br>');
$('#prof').clone().insertAfter("#prof").before('<br>');
});
//this part here generates number 1-31 and adds into month and days
i=0;
for(i=1; i<=31; i++){
$('#dayselect').append($('<option>', {value:i, text:i}));
if(i<=12){
$('#monthselect').append($('<option>', {value:i, text:i}));
}
}
//this code here generates years, will work for the last, 120 years
year=(new Date).getFullYear()-120;
i = (new Date).getFullYear()-16;
for(i; i>=year; i--){
$('#yearselect').append($('<option>', {value:i, text:i}));
}
//Regex Patterns
var pass = /^[a-z0-9\.\-\)\(\_)]+$/i;
var uname = /^[a-z0-9\.\-]+$/i;
var mname = /^[a-z ]+$/i;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
//When the Last Name texbox is changing this will be invoked
$("#fname").keydown(function(){
//comparing the above regex to the value in the texbox, if not from the box then send error
if(!mname.test($("#fname").val())){
//fill the textbox label with error
document.getElementById("fname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid FirstName</font>";
$("#fname").css("border-color","rgba(255,0,0,.6)");
works=false;
}
else{
$("#fname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("fname_error").innerHTML="";
works = true;
}
});//end of fname onchange
//When the Last Name texbox is changint this will be invoked
$("#lname").keydown(function(){
//comparing the above regex to the value in the texbox
if(!mname.test($("#lname").val())){
//fill the textbox label with error
document.getElementById("lname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid LastName</font>";
$("#lname").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
$("#lname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("lname_error").innerHTML="";
works = true;
}
});//end of lname on change
//When the userid textbox is chaning,this will be invoked
$("#userid").keydown(function(){
//comparing the above regex to the value in the texbox
if(!uname.test($("#userid").val())){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid UserId</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
works=false;
}
/*
else if($("#userid").val().length<4){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Minimum user length is 4</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
//disable the submit button
//$('#submitbtn').attr('disabled','disabled');
works=false;
}
*/
else{
$("#userid").css("border-color","rgba(0,0,0,.3)");
$.post("user_test/user_email_test.php",
{
// userid: $("#userlogin").val(),
userid: $("#userid").val(),
},
function(data,status){
document.getElementById("userid_error").innerHTML=data;
});
works = true;
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#memail").keydown(function(){
//comparing the above regex to the value in the texbox
if(!emailReg.test($("#memail").val())){
//fill the textbox label with error
document.getElementById("email_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid Email</font>";
$("#memail").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
works = true;
$.post("./user_test/user_email_test.php",{
useremail: $("#memail").val(),
},
function(data,status){
document.getElementById("email_error").innerHTML=data;
$("#memail").css("border-color","rgba(0,255,0,.3)");
works = true;
});
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#pwd2").keyup(function(){
//checking length of the password
if($("#pwd2").val().length<10){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Please enter a password minimum 10 characters</font>";
//$('#submitbtn').attr('disabled','disabled');
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
works=false;
}
//checking if the password matches
else if($("#pwd1").val()!=$("#pwd2").val()){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Passwords do not match</font>";
//$('#submitbtn').attr('disabled','disabled');
works=false;
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
}
else{
$("#pwd1, #pwd2").css("border-color","rgba(0,0,0,.3)");
document.getElementById("pwd_error").innerHTML="";
//comparing the above regex to the value in the texbox and checking if the lenght is atleast 10
if(!pass.test($("#pwd2").val())){
//fill the textbox label with error
document.getElementById("pwd_error").innerHTML="<font color='red' size='1px' family='verdana'>Your password contains invalid character, Please use: a-z 0-9.( )_- only</font>";
$("#pwd1, #pwd2").css("border-color","rgba(255,0,0,.6");
works = false;
}
else{
$("#pwd1 , #pwd2").css("border-color","rgba(0,255,100,.6)");
works = true;
}
}
});//end of change
});//end of document ready
</script>

Getting the ID of a radio button using JavaScript

Is there a way to get the ID of a radio button using JavaScript?
So far I have:
HTML
<input type="radio" name="fullorfirst" id="fullname" />
JavaScript
var checkID = document.getElementById(fullname);
console.log(checkID);
It outputs as null.
Essentially what I want to do is:
document.getElementById(fullname).checked = true;
...in order to change the radio button fullname to be checked on page load.
you should put fullname between quotes, since it's a string:
document.getElementById("fullname");
function checkValue() // if you pass the form, checkValue(form)
{
var form = document.getElementById('fullname'); // if you passed the form, you wouldn't need this line.
for(var i = 0; i < form.buztype.length; i++)
{
if(form.buztype[i].checked)
{
var selectedValue = form.buztype[i].value;
}
}
alert(selectedValue);
return false;
}
Hope this helps.
JavaScript Solution:
document.getElementById("fullname").checked = true;
Jquery Solution:
$("#fullname").prop("checked", true);

Get variable via user input

I want that the user can see the value of a variable by writing it's name in a textarea, simpliefied:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"
Is it even possible to output (in this example) "300$"?
Thanks for help!
Instead of seprate variables, use an object as an associative array.
var variables = {
'money': '300$'
}
var input = 'money';
alert(variables[input]);
You can use an object and then define a variable on the go as properties on that object:
var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);
A simple way,you can still try this one :
var money = "300$";
var input = "money"; //user wants to see money variable
alert(eval(input)); //This would alert "money"
Here is an answer who use the textarea as asked.
JSFiddle http://jsfiddle.net/7ZHcL/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Variable name:</label>
<textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
</p>
<input type="submit" value="Submit" />
</form>
<div id="result"></div>
JQuery
$(function () {
// Handler for .ready() called.
var variables = {
'money': '300$',
'date_now': new Date()
}
//Detect all textarea's text variation
$("#varWanted").on("propertychange keyup input paste", function () {
//If the text is also a key in 'variables', then it display the value
if ($(this).val() in variables) {
$("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
} else {
//Otherwise, display a message to inform that the input is not a key
$("#result").html('"' + $(this).val() + '" is not in the "variables" object');
}
})
});

Unable to get an event interrupter for preventing form submission to work corrctly in a basic JavaScript and PHP tutorial

I am trying to learn JavaScript, PHP and some basic client-side form validations in trying to build this basic JavaScript tutorial that interacts with PHP and HTML. WHat I am trying to do is interrupt a form submission event, i.e. user forgets to enter a valid email format in the email submission input and clicks on the submit button which should then display an error message and not allow the form to be submitted. But I can't get this to work for me. What happens is that I am instead taken to the support_process.php page when that should not happen. Any help at all would be greatly appreciated.
Here is my index.html code for the form:
<div>
<form id="frmSupport" name="frmSupport" method="post" action="support_process.php">
<fieldset id="fastSupport">
<legend><strong>Fast Support</strong></legend>
<p>If you've already booked the Singing Rails Girls coach,</br> and have not gotten a confirmation number,</br> drop us a line and we'll respond within 24 hours.</p> </p>
<p>
<label for="email">Email:</label>
<input type="text" value="your email" name="name" id="email" tabindex="10" />
<p>
<span id="errorMsg"></span>
</p>
<input type="submit" value="Submit">
</p>
<p><b>Ed's "Blah Blah Blah" Tour Status</b></p>
<label for="tourStatus" class="inline">
<input type="radio" name="tour status" value="booked" id="tourStatus_0" tabindex="40" />Ed already toured here
</label>
<label for="tourConf" class="inline" >
<input type="radio" name="tour conf" value="paid" id= "tourStatus_1" tabindex="50" />Ed confirmed his tour date
</label>
</br>
</fieldset>
</form>
</div>
Comments Section
Comments:
<script src="myscript.js">
</script>
And here is my corresponding JavaScript file:
//alert("Hello, world!"); // this is a JavaScript alert button //
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro...");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
// Handling the form submit event
document.getElementById("frmSupport").onsubmit = function(){
//prevent a form from sumbitting if no email.
if (document.getElementById("email").value == "") {
document.getElementById(errorMsg).innerHTML = "OOPS!";
//to stop the form from submitting:
return false;
}else {
//reset and allow form submission:
document.getElementById("errorMsg").innerHTML = "";
return true;
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers();
// This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White- Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
var intervalHandle = setInterval(changeImage, 5000);
myImage.onclick = function() {
clearInterval(intervalHandle);
}
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
And here is my corresponding php file for the event interrupter (for refusing to allow the form to be submitted if user leaves email field blank or something):
<?php
//some php script can go here
echo "This is the support confirmation page...sorry, nothing fancy here!"
?>
<h1>Thank you, we will contact you shortly!</h1>
<a href="index.html" target="_blank" >Back</a>
<?php
// More php code can go here, and so forth and so on..
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_GET); */
error_log(message);
?>
Here's a problem:
if (document.getElementById("email").value == "") {
document.getElementById(errorMsg).innerHTML = "OOPS!";
//to stop the form from submitting:
return false;
}else {
//reset and allow form submission:
document.getElementById("errorMsg").innerHTML = "";
return true;
}
In the first part of the if, you're trying to get a reference to the errorMsg element using a non-existent variable:
document.getElementById(errorMsg).innerHTML = "OOPS!";
In the second, you're accessing the element by its id properly:
document.getElementById("errorMsg").innerHTML = "";
You need to surround 'errorMsg' with single or double quotes.
You should definitely look into using a debugger to help you find problems like these. Chrome Developer Tools are a good place to start.

Categories

Resources