cant get the value of input with oop js - javascript

Hello I am trying to get the input value from a form input using oop js.
When I get the username I want to validate it but I cant get the value of username.
when I console.log(username); I either get undefined or the html markup instead of the value. What am I doing wrong?
my form
<form action="" method="post">
<input type="text" name="username" id="username">
</form>
and my js
<script type="text/javascript">
validateForm = {
username : $.trim($('#username').val().toUpperCase().replace(/\s+/g, '')),
checkUsernameValid : function() {
$('#username').on('keyup change', function() {
console.log(this.username);
if (/^[a-zA-Z0-9]*$/.test(this.username) == false) {
alert('bad')
} else {
alert('good');
}
});
}
};
validateForm.checkUsernameValid();
</script>

Call either this.username = $.trim($('#username').val().toUpperCase().replace(/\s+/g, '')); or this.username = $('#username').val(); inside your keyup event to set the value
validateForm = {
username : $.trim($('#username').val().toUpperCase().replace(/\s+/g, '')),
checkUsernameValid : function() {
$('#username').on('keyup change', function() {
this.username = $.trim($('#username').val().toUpperCase().replace(/\s+/g, ''));
console.log(this.username);
if (/^[a-zA-Z0-9]*$/.test(this.username) == false) {
// alert('bad')
} else {
// alert('good');
}
});
}
};
validateForm.checkUsernameValid();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<input type="text" name="username" id="username">
</form>

I either get undefined or the html markup instead of the value.
As you have set the name and id attributes so it gets available in the global scope as a whole so, html element gets logged in console.
You should not bind the event in the method such way. You can call the method in the bound event and make the method to accept the value as an argument such as:
validateForm = {
username: $.trim($('#username').val().toUpperCase().replace(/\s+/g, '')),
checkUsernameValid: function(value) { // 2. get the value
this.username = value; // 3. set the value
if (/^[a-zA-Z0-9]*$/.test(this.username) == false) {
console.log('bad')
} else {
console.log('good');
}
}
};
$('#username').on('keyup change', function() {
validateForm.checkUsernameValid(this.value); // 1. pass the input value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<input type="text" name="username" id="username">
</form>

Related

How trigger validation on a textbox when a button is pressed?

I've got two text boxes for first and last name. I also have a button to save the data. The button has an event handler where it grabs the data from the fields and posts them with an ajax call to my API, using jquery.
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Here is an example which may help you:
$('#save').click(function() {
var errors = [];
var name = $('#name').val();
var vorname = $('#vorname').val();
if (!name) {
errors.push("Name can't be left blank");
}
if (!vorname) {
errors.push("Vorname can't be left blank");
}
if (errors.length == 0) {
console.log('Ajax started');
//put here your ajax function
} else {
for (var i in errors) {
console.log(errors[i]);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" id="name"><br>
<input placeholder="Vorname" id="vorname"><br>
<button id="save">Save</button>
here is an example using the popular add on jquery validate. https://jqueryvalidation.org/
click the run snippet button below
$(document).ready(function() {
$("#form").validate({
rules: {
"firstname": {
required: true,
},
"lastname": {
required: true,
}
},
messages: {
"firstname": {
required: "Please, enter a first name"
},
"lastname": {
required: "Please, enter a last name"
},
},
submitHandler: function(form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<button type="submit">Submit</button>
</form>
Without seeing your code, it is very difficult to guess the correct scenario to provide examples for.
Given the following HTML:
<form>
<input type="text" class="text1">
<input type="text" class="text2">
<button type="button">Send</button>
</form>
You could use this for the jQuery part:
$('button').click(function() {
var txt1 = $(this).siblings('.text1').val();
var txt2 = $(this).siblings('.text2').val();
if (txt1.length && txt2.length) {
// do your ajaxy stuff here
} else {
alert("Imput some friggin' text!");
}
});
$(this) selects the button clicked.
.siblings('.text1') selects the input with class text1 inside the same block as the clicked button.
https://jsfiddle.net/sg1x0c3q/7/
As per my comments I would recommend using a form. But if you want a pure JS solution here you go. (if you want a form based solution just ask)
// convert all textareas into key value pairs (You can change the selector to be specific to your markup)
const createPayload = () => {
return [].slice.call(document.querySelectorAll('textarea')).reduce((collection, textarea) => ({
...collection,
[textarea.name]: textarea.value
}), {})
}
// Compare Object values against values that are not falsy (you could update the filter with a RegExp if you wanted more complicated validation)
const objectHasAllValues = obj => {
return Object.values(obj).length == Object.values(obj).filter(value => value).length
}
// If all key value pairs are not falsy then submit
window.submit = () => {
const payload = createPayload()
if (objectHasAllValues(payload)) {
fetch('/your/api', payload)
}
}
This solution presumes that your API expects a JSON payload. If you are expecting to send form data then you would need to use the formData js api.
This scales and doesn't need jQuery :)
Working example here https://jsfiddle.net/stwilz/dxg29mkj/28/
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Answer to form validation. I assume that First name and Last name can only contain alphabets ,i.e., only a-z and A-Z.
//This function will trim extra whitespaces form input.
function trimInput(element){
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s){
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name){
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#myForm').submit(function(e){
e.preventDefault();
var fname = $(this).find('input[name="fname"]');
var lname = $(this).find('input[name="lname"]');
var flag = true;
trimInput(fname);
trimInput(lname);
if(isEmpty($(fname).val()) === false || isName($(fname).val()) === false){
alert("First name is invalid.");
flag = false;
}
if(isEmpty($(lname).val()) === false || isName($(lname).val()) === false){
alert("Last name is invalid.");
flag = false;
}
if(flag){
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" id="myForm" method="post" action="#">
<input type="text" name="fname" placeholder="Firstname">
<input type="text" name="lname" placeholder="Last Name">
<input type="submit" name="submit" value="Submit">
</form>
I am not using the <form> tag for this.
Then the code will be like
//This function will trim extra whitespaces form input.
function trimInput(element) {
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s) {
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name) {
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#submit').click(function() {
var fname = $('#fname');
var lname = $('#lname');
var flag = true;
trimInput(fname);
trimInput(lname);
if (isEmpty($(fname).val()) === false || isName($(fname).val()) === false) {
alert("First name is invalid.");
flag = false;
}
if (isEmpty($(lname).val()) === false || isName($(lname).val()) === false) {
alert("Last name is invalid.");
flag = false;
}
if (flag) {
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname" placeholder="Firstname">
<input type="text" id="lname" name="lname" placeholder="Last Name">
<button type="button" id="submit" name="submit">Submit</button>
Check the code on jsFiddle.
Hope this will be helpful.

validation in form not working

I don't know what im doing wrong, i have a form and using this function to check if the input is empty...what Iam trying to do is to highlight the field by adding a class to the text field...but if i add this line
name.addClass("empty");
to the function, the function dont work
function register()
{
if(document.myForma.userid.value == '')
{
name = $("#userid");
document.myForma.userid.focus();
$("#empty").html("This field is required")
name.addClass("empty");
return false;
}
}
Declare your name variable as local, or use a different name for it, - global window.name already exists and is not changeable.
console.log(name);
function register() {
if (document.myForma.userid.value == '') {
var name = $("#userid");
document.myForma.userid.focus();
$("#empty").html("This field is required");
name.addClass("empty");
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForma" name="myForma" onsubmit="return register();">
<input id="userid" type="text" />
<div id="empty"></div>
<input type="submit" />
</form>

How to pass value of textbox to a method in controller?

In Angularjs, I'm trying to pass a value from a textbox to method written in controller as below
#Try 1
<input type="text" ng-blur="isExists(this.value)">
and within my controller I have
$scope.isExists = function (theValue) {
alert(theValue);
};
It is not working.
#Try 2
<input type="text" ng-model="username" ng-blur="isExists()">
and within controller
$scope.isExists = function () {
alert($scope.username); // returns undefined
};
How to pass value from ng-blur to a method within a Controller?
Updates:
Any reason why the valueis not seen in the textbox?
<input type="text" ng-model="username" ng-blur="isExists()">
Fiddle
Try2 should not return undefined if the <input type="text"
is filled with at least one character.
You can append {{ username }} on the html page just for debug purporses to make sure it was well binded.
<input type="text" name="userId" id="txtid" />
<script type="text/javascript">
$(document).ready(function () {
$('#txtid').blur(function () {
debugger;
var id = $('#txtid').val();
window.location = "/Home/CreateSupplier/?userid=" + id;
});
});
</script>
In controller
public ActionResult CreateSupplier(string userid)
{
if (userid != null)
{
return Content("Received Username:" + userid);
}
return View(thesupplierList);
}

Not returning a value for some reason

Basically I have a script the function "hola ()" that should return the value of 1 if the radio button value is 1. But for some reason when I try to get the return value in another function i never get it.
The form works perfectly.. the only issue is that it doesnt return the value
Can anyone tell me what i did wrong?? thanks
$(document).ready(function(){
function hola() {
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
return 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
})
}
$("#iForm").submit( function(event){
event.preventDefault();
var user = $("input[name=username]").val();
var password = $("input[name=password]").val();
var dbName = $("input[name=dbName]").val();
var server = $("input[name=server]").val();
$.get("1.php",
{username: user, password: password, dbName: dbName, server: server },
function(data){
if (data == "The table PAGE exists" || data == "The table SUBJECTS exists" || data == "The table USERS exists" ) {
// CALLING THE hola () function and expecting a return
var opt = hola();
$("p").html(data + opt);
}
}
)
})
})
HTML
<!-- Yes or No form -->
<form name="yN" style= "display: none; margin-left: auto; margin-right: auto; width: 6em">
<input type="radio" name="yN" value="1">yes</input>
<input type="radio" name="yN" value="0">no</input>
<button id=1 >click me!</button>
</form>
<!-- Login Form -->
<form id="iForm" style= "display: show">
<label id="username" >Username</label>
<input id="username" name="username"/>
<label id="password">Password</label>
<input id="password" name="password" />
<label id="server" >Server</label>
<input id="server" name="server"/>
<label id="dbName" >dbName</label>
<input id="dbName" name="dbName"/>
<input type="submit" value="submit" />
</form>
<p> </p>
Event handlers cannot return values because they're called asynchronously*.
Your existing hola() function will return immediately and the return statements in the click handlers are only called much later, i.e. when the button is clicked.
My approach would be this, using jQuery deferred objects (jQuery 1.6+):
function hola() {
var def = $.Deferred();
// show the popup confirm form
...
$('input[type=radio]').click(function() {
// determine return value
...
// send it back to anything waiting for it
def.resolve(retval);
});
// return a _promise_ to send back a value some time later
return def.promise();
}
$.get("1.php", { ... }).done(function(data) {
if (...) {
hola().done(function(opt)) { // will be called when the promise is resolved
$("p").html(data + opt);
});
}
});
If you prefer, instead of returning the opt value you could use def.reject() to indicate "non-acceptance" and then use a .fail handler to register a handler to be called for that condition.
You return 1 only in the click function of the radiobutton.
If you want to have a function "hola" that returns 1 if the radiobutton is checked, you simply need something like this:
function hola() {
return $("input:radio[name='yN']:checked").val();
}
hola does not even have a return statement. That's the reason for its not returning anything (more precisely: returning undefined always).
A JavaScript function that does not contain a return statement at all or whose all return statements are within nested functions will never return anything but undefined.
Your are tring to return the value from withing the click callback function. Move the return outside that:
function hola() {
var result;
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
result = 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
});
return result;
}

How to convert from javascript form action to jquery?

I have a code javascript of a action form:
<form name="myform" onsubmit="return OnSubmitForm();" method="post">
<input type="text" value="" id="type" />
<input type="submit" value="submit" />
</form>
And javascript:
function OnSubmitForm() {
var type = document.getElementById('type').value;
if(type == '1') {
document.myform.action = "index.php?type=1";
}
if(type == '2') {
document.myform.action = "index.php?type=2";
}
return false;
}
How to convert this javascript to jquery, please this ideas?
$("form[name='myform']").submit(function() {
this.action = "index.php?type=" + this.type.value;
return false;
});
form[name='myForm'] selects a form with the name myForm.
Calling .submit(function () { ... }) binds an event handler for the submit event.
Inside the function, this refers to the form.
Example: http://jsfiddle.net/4SZrH/ (check out the form action in Firebug or similar).
First note that this function always returns false, so your form will never submit. But to answer your question, you could use jQuery's submit event
$("form[name='myform']").submit(function(){
var type = this.type.value;
if (type === '1' || type === '2')
this.action = "index.php?type=" + type;
return false;
});
Or more simply:
$("#myForm").submit(OnSubmitForm);
Also note that, for dom level 0 event handlers, you don't want the return statement inline. In the future just do
<form name="myform" onsubmit="OnSubmitForm();"
And let OnSubmitForm return true or false
Finally, note that in JavaScript, functions starting with a capital letter by convention denote a constructor. Consider renaming this function to onSubmitForm

Categories