How to check input values in javascript - javascript

function checkNullSearch(e) {
if ($('#searchInput').val() === "") {
$('#searchInput').attr("value", "null");
}
}
script.js
<form role="form" id="form-arya">
<div class="form-group">
<div class="panel panel-primary searchPanel">
<div class="input col-sm-12">
<input type="text" class="form-control" id="searchInput"
name="searchInput"
aria-describedby="Not Null"
placeholder="Search"
required>
</div>
<div class="inputAndButtons">
<div class="standartSearch">
<button class="btn btn-arya btn-success" type="submit" name="ara"
value="standart">
<i class="glyphicon glyphicon-search" aria-hidden="true" onclick="checkNullSearch(this)"></i>
Search
</button>
</div>
</div>
</div>
</div>
</form>
xxx.html
Sometimes it works, sometimes it doesn't work
I want to on the input control to do. I want return "null" if input is empty value's

Change your button code like below:-
<button class="btn btn-arya btn-success" type="submit" name="ara" value="standart" onclick="checkNullSearch(this)"><i class="glyphicon glyphicon-search" aria-hidden="true"></i>Search</button>
And use $.trim() in your jQuery code
function checkNullSearch(e) {
if ($.trim($('#searchInput').val()) == "") {
$('#searchInput').attr("value", "null");
}
}

Check for inputs whitespace characters.There may whitespace characters even though the input seems to be empty.Try to remove those whitespaces using the trim() method

you can use this code to get input value
function getInputValue(id) {
return document.getElementById(id).value.trim();
}
use
getInputValue("searchInput")

Your way is not wrong. You are using JQuery hence if you import jquery file in your page, It will work everytime. But instead of this code
$('#searchInput').attr("value", "null");
You have to use like this.
$('#searchInput').val('');
And if you want to use javascript you can check following
document.getElementById("#searchInput").value

before check null, you need to remove white space in input text. So you can use trim function
var str = " Hello World! ";
alert(str.trim());
if the browser does not support trim function, use following way
function myTrim(x) {
return x.replace(/^\s+|\s+$/gm,'');
}
function myFunction() {
var str = myTrim(" Hello World! ");
alert(str);
}

This worked for me.
function checkNullSearch() {
if ($(#searchInput').val().trim() == "") {
// it's empty
}
}

Related

How To Disable Button by Using Javascript

I trying to write a booking appointments for my website. But i have something need to help from you.
this is my HTML for field to input:
<div class="form-group second_box">
<form id="submit" style="display:inline-block" method="post">
<label for="submit" class="control-label">
<?= lang('submit') ?> *</label>
<input type="number" name='otp' id="otp" class="required form-control" placeholder="write your code here" required="required" >
<span id="otp_error" class="field_error"></span>
</div>
this is my HTML button:
<button type="button" id="button-next-3" class="btn button-next btn-primary" onsubmit="submit_otp()"
data-step_index="3"<?= lang('next') ?>
<span class="glyphicon glyphicon-forward"></span>
</button>
and this is my Jacascript from another file:
function submit_otp(){
$('#wizard-frame-3 .has-error').removeClass('has-error');
$('#wizard-frame-3 label.text-danger').removeClass('text-danger');
var otp=jQuery('#otp').val();
jQuery.ajax({
url:'../../../Code_Verification/check_otp.php',
type:'post',
data:'otp='+otp,
success:function(result){
if(result=='yesFalse'){
jQuery('#otp_error').html('Please enter your valid code');
}
if(result=='yesTrue'){
jQuery('#otp').html('Your code is correct');
}
if(result=='not_exist'){
jQuery('#otp_error').html('Please enter valid otp');
}
}
});
}
--> I using php in check_otp.php to connect with my database to comparing the value return. if the input in the second_box equal with the value i saved in the database that's mean the customer can go to next step. if they give input wrong with the value in database that's mean they cannot continue. but i don't know how to give it's logic together.
and this is the next button call in javascript file:
$('.button-next').click(function (){
if ($(this).attr('data-step_index') === '3') {
if (!_validateCustomerForm()) {
return; // Validation failed, do not continue.
}
}
--> thanks all for help.
Since you're using jQuery, you can try
$("#button-next-3").attr("disabled", true);
Use .attr() to set disable attribute
Usage $(selector).attr("disabled", true)
In your case : $("#button-next-3").attr("disabled", true)
function myButton() {
document.getElementById("myBtn").disabled = true;
}
<html>
<body>
<button id="myBtn">My Button</button>
<p>Click the button below to disable the button above.</p>
<button onclick="myButton()">Try it</button>
</body>
</html>

Create HTML text in an HTML form and open up the text in a Javascript alert box

I'm new to coding and need to create HTML text in an HTML form on a page and open up the text in a Javascript alert box. I've tried various code to no success. Here is what I've come up with so far which does not create a pop up alert box:
Here is the HTML and the JS:
Function myfunction1()
{
Let myfun1 = document.getElementById('sec1-input').value;
Alert(myfun1);
}
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button id="sec1-btn1" type="button" class="btn btn-primary">Alert Me!</button>
I'm not sure what do you want, but I'll show you how to make an alert window exactly as you're asking.
First of all you must consider several mistakes that you are making. JavaScript does not recognize the word Function because it is capitalized. The function keyword must be lowercase.
Here I leave you a referring link with JavaScript reserved words: https://www.w3schools.com/js/js_reserved.asp
On the other hand, I see that you are not using the form tag, which leads to two problems: technical and semantic. Here I leave you another link with reference to forms: https://www.w3schools.com/html/html_forms.asp
Finally, to achieve what you want you need to work with events, especially with the click event. Here I will leave you a reference link and the solution you want:
let button = document.querySelector('#sec1-btn1');
button.addEventListener('click', function(e) {
let val = document.querySelector('#sec1-input').value;
alert(val);
});
<form>
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input" />
</div>
<button id="sec1-btn1" type="button" class="btn btn-primary">
Alert Me!
</button>
</form>
You have not called the function anywhere. For it to work you need to use a listener.
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button onclick="myfunction1()" id="sec1-btn1" type="button" class="btn btn-primary">Alert Me!</button>
<script>
function myfunction1() {
let myfun1 = document.getElementById('sec1-input').value;
alert(myfun1)
}
</script>
I added the onClick listener to button and now it works.
javaScript is case sensitive
function myfunction1()
{
let myfun1 = document.getElementById('sec1-input').value;
alert(myfun1);
}
<div class="form-group">
<label for="sec1-label"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button id="sec1-btn1" type="button" onClick="myfunction1()" class="btn btn-primary">Alert Me!</button>
also IDs of elements should not be the same , to assign same selector , use class and you also need to give your function to your element's event listener
You should not start javascript functions like alert with capital letters.
Put this piece of code instead of your button:
<button id="sec1-btn1" type="button" class="btn btn-primary" onclick="myfunction1()">Alert Me!</button>

How come my input box's value isn't being returned?

Using twitter bootstrap, I have created a button with an input box beside it. I'm trying to then access that value in my view using jQuery but for some reason I can't get anything back besides "undefined". Here's my code:
jQuery:
var browserInput = $("#browserInput").val();
console.log(browserInput);
Html:
<div class="col-lg-4">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" id="addBrowser">
<span class="glyphicon glyphicon-plus"></span>
Add
</button>
</span>
<input id="browserInput" type="text" class="form-control" style="display: none;" >
</div>
</div>
If this is your actual code layout, you won't get a value because the DOM isn't loaded at the time you are requesting the value.
You should try to wrap your function in document ready
$(document).ready(function() {
var browserInput = $("#browserInput").val();
console.log(browserInput);
});
If you want to have the value on keyup or interaction with the input box, you can also do it like
$(document).ready(function() {
$('#browserInput').on('keyup',function() {
var browserInput = $("#browserInput").val();
console.log(browserInput);
});
});
I'm going to undelete my answer because apparently it helped the poster solve his issue...
<input id="browserInput" type="text" value="" class="form-control" style="display: none;" />
Seems that having the value="" in the <input> tag made a difference for him.
I wonder if he meant "" instead of undefined.

script that checks text field do not work with chrome

I have a form and java script that checks if text filed was not empty. problem is, code works with IE and Firefox but do not work with chrome.
<form action="editor.php?id=<?=$id_book?>" method="post" name="form1" onsubmit="return check_form(this)" >
<script language="javascript">
function check()
{
if ((document.all.title.value==""))
{
alert("Отсутствует название книги!");
}
if ((document.all.price.value==""))
{
alert("Отсутствует цена книги!");
}
if ((document.all.descrip.value==""))
{
alert("Отсутствует описание книги!");
}
else
{
document.all.form1.submit();
}
}
</script>
<div class="list-group">
<div class="input-group input-group-lg">
<span class="input-group-addon"><div class="inp_width">Название:</div></span>
<input type="text" name="title" class="form-control" value="<?=$value['title']?>">
</div><br />
<div class="input-group input-group-lg">
<span class="input-group-addon"><div class="inp_width">Цена:</div></span>
<input type="text" name="price" class="form-control" value="<?=$value['price']?>">
</div><br />
<div class="input-group input-group-lg">
<span class="input-group-addon"><div class="inp_width">Описание</div></span>
<textarea type="text" name="descrip" class="myform-control" rows="5"><?=$value['descrip']?></textarea>
</div><br />
<?php endforeach; ?>
<div class="col-md-12">
<div class="col-md-2"><button type="button" value="Submit" class="btn btn-primary" onclick="check()">Редактировать</button>
</form>
</div>
any ideas? More problem is that if I have just one filed check in chrome, scripts works fine. Submit button do not work only if I need to check several fields.
UPDATE: sorry guys... everything works fine... copy-paste will kill me... type button should be "Submit" instead of "button"... next time I'll should be more careful coping code:)
Your IF statements look incorrect. Only the last IF statement will stop the submit from happening, as that is the only call that the "else" step is associated with. For javascript please try the following format:
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is true
}
additionally, if you want to check multiple values and if any of the values don't exist you should try some sort of flag. Example:
If (document.all.title.value==""){
message += "Title is missing";
}
If (document.all.price.value==""){
message += "Price is missing";
}
If (message == ""){
document.all.form1.submit();
}else{
alert(message)
}
Markup errors aside (see my comment), document.all is IE/MSHTML-proprietary and now deprecated (for some reason Mozilla adopted it a few years ago). Your code should look as follows when standards-compliant:
<form … onsubmit="return check_form(this)">
<script type="text/javascript">
function check_form (form)
{
var elements = form.elements;
if (elements["title"].value == "")
{
window.alert("Отсутствует название книги!");
return false;
}
if (elements["price"].value == "")
{
window.alert("Отсутствует цена книги!");
return false;
}
if (elements["descrip"].value == "")
{
window.alert("Отсутствует описание книги!");
return false;
}
}
</script>
…
<button type="submit" value="Submit" class="btn btn-primary">Редактировать</button>
</form>
Note that the function returns false if there is an error, preventing the form from being submitted because the return value is returned to the onsubmit event handler (which I presume was the intention; you called, but did not define the check() function there). You should not bother the user with several alert()s if there are several errors, but at most collect the error messages for one alert(). You can use an Array of string values for that.
However, given that new Firefox versions prevent the user from seeing the document while the alert() is displayed, you should avoid alert() and display the error messages in the document instead. A common approach is to highlight the erroneous fields using scripted CSS, and put the message that says what is wrong with the particular field either in a box for the entire form or next to the offending control. Also consider HTML5 form validation.

Set Value of Input Using Javascript Function

I'm currently using a YUI gadget. I also do have a Javascript function to validate the output that comes from the div that YUI draws for me:
Event.on("addGadgetUrl", "click", function(){
var url = Dom.get("gadget_url").value; /* line x ------>*/
if (url == "") {
error.innerHTML = "<p> error" /></p>";
} else {
/* line y ---> */
/* I need to add some code in here to set the value of "gadget_url" by "" */
}
}, null, true);
Here is my div:
<div>
<p>URL</p>
<input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input"/>
<input type="button" id="addGadgetUrl" value="add gadget"/>
<br>
<span id="error"></span>
</div>
As you can see my question is, how can I set the value of gadget_url to be ""?
Javascript
document.getElementById('gadget_url').value = '';
jQuery
$("#gadget_url").val("");
YUI
Dom.get("gadget_url").set("value","");
document.getElementById('gadget_url').value = '';
The following works in MVC5:
document.getElementById('theID').value = 'new value';
Depending on the usecase it makes a difference whether you use javascript (element.value = x) or jQuery $(element).val(x);
When x is undefined jQuery results in an empty String whereas javascript results in "undefined" as a String.
document.getElementById('gadget_url').value = 'your value';
I'm not using YUI, but my issue was that I had duplicate ID's on the page (was working inside a dialog and forgot about the page underneath).
Changing the ID so it was unique allowed me to use the methods listed in Sangeet's answer.
Shortest
gadget_url.value=''
addGadgetUrl.addEventListener('click', () => {
gadget_url.value = '';
});
<div>
<p>URL</p>
<input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input" value="some value" />
<input type="button" id="addGadgetUrl" value="add gadget" />
<br>
<span id="error"></span>
</div>
This is the shortest working solution (JSFiddle).

Categories