Javascript is working fine but not in jQuery [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This code works fine for me in Javascript.
function check_u() {
var errormessage = document.getElementById("errorname");
var user = document.forms["login"]["user"].value;
if (user == null || user == "") {
errormessage.innerHTML = "Please enter your user id";
} else {
errormessage.innerHTML = "";
}
}
function check_p() {
var errormessage = document.getElementById("errorpass");
var pass = document.forms["login"]["password"].value;
if (pass == null || pass == "") {
errorShow.innerHTML = "Password cannot be blank";
} else {
errorShow.innerHTML = "";
}
}
My html is :
<input type="text" name="user" autocomplete="off" onBlur="check_u()" />
<input type="text" name="password" autocomplete="off" onBlur="check_p()" />
<div id="errorname" />
I have written an alternative for this code in jQuery. In JavaScript it works fine but in jQuery when I don't enter any input first time it is showing error message. I enter some value to it then it clears the error message. Now if I am leaving the input blank the error message doen't show up. Here is my jQuery code:
function check_u(){
var fieldValue = $("input[name=user]").val();
if(fieldValue==""||fieldValue==null){
$("#errorname").html('<div id = "error_left"></div>'+
'<div id = "error_right"><p>This is a required field</p></div>');
}else{
$("#errorname").hide();
}
}
Why, if on repeated calls, does my errorname div not show up?
Does .hide() do more than just clear out the div?

In the javascript else clause, you are clearing the contents, but in the jQuery clause you are hiding the entire error element.
Instead of
$("#errorname").hide()
try
$("#errorname").html("")

You need to show errorname after setting the html
$("#errorname").html('<div id = "error_left"></div>'+
'<div id = "error_right"><p>This is a required field</p></div>').show();
You are hiding the errorname div in case of a valid entry, then if value becomes invalid then you need to set the error message and set the visibility to of the div.
demo: Plunker

Your onblur is calling check_u() but your other jQuery example's function name is checkUser()

Related

My java code should make a list but it doesn't [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
My java code is not working I'm watching a code video for to do list this code should make a list when I click a button but it doesn't please help
enter image description here
<script>
document.querySelector('#push').onclick =
function() {
if (document.querySelector('#newtask input').
value.length == 0){
alert("please enter task");
}
else {
document.querySelector('#task').innerHTML
+= '<div class ="task"><span id ="taskname">$
{document.querySelector("#newtask input").
value}</span> <button
class ="delete">×</button></div>';
}
</script>
</body>
</html>
Step 1:
createTextNode
Step 2:
Append it inside of body(I have done in #main for div)
const main = document.querySelector("#main");
const inputText = document.querySelector("#textInput");
const taskBtn = document.querySelector("#addTask");
function addTask(taskData) {
const task = document.createTextNode(taskData);
main.appendChild(task);
main.appendChild(document.createElement("br"));
}
taskBtn.addEventListener("click", () => {
if (inputText.value == "") {
alert("please enter task!!");
} else {
addTask(inputText.value);
inputText.value = "";
}
});
<div id="main">
<input type="text" id="textInput" placeholder="Enter task" />
<button id="addTask">Add task</button><br />
</div>
While the method in the accepted answer does produce the desired output, it doesn't answer the original question as to why the code does not work. There are actually a few things wrong with it:
First, your click handler function declaration was missing it's closing };. You can catch mistakes like this by running your code through linting tools such as JSHint.
Second, you should not brute force the onclick method of an element. Doing so only allows for one function to be attached. Instead you can use Element.addEventListener to attach a handler to the click event.
Finally, you tried to use a placeholder expression ${...} when setting innerHTML. These can only be used inside of template literals. The character used to create this type of variable should the backtick ( ` ) however, you have used single quotes ( ' ).
The correct way to write your code would be:
document.querySelector('#push').addEventListener('click', event => {
if (document.querySelector('#newtask input').value.length == 0) {
alert("please enter task");
} else {
document.querySelector('#task').innerHTML += `
<div class="task">
<span id ="taskname">
${document.querySelector("#newtask input").value}
</span>
<button class ="delete">×</button>
</div>
`;
}
});

javascript code to display an alert message after 15 keystrokes [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
In my project, there is a text box to enter the password and the password characters limit is up to 15. So, I want to display an alert message through javascript as soon as the user tries to enter the 16th character. Please help!
Try this.
function alrtMsg() {
var x = document.getElementById("pwd").value;
if(x.length > 16){
alert("maximum length is 16");
document.getElementById("pwd").value = '';
}
}
<html>
<body>
<input type="password" id="pwd" onkeyup="alrtMsg()">
</body>
</html>
Try this on Javascript:
document.getElementById("password").onkeyup = function() {
var text = document.getElementById("password").value
if(text.length> 15){
alert("too much text")
}
};
<input id="password" type="password" placeholder="password">
you need to mention your code what you tied. Anyway if you don't know try this code
<input type="text" onkeypress="myFunction(this)" maxlength="5">
<script>
function myFunction(e) {
var maxlen= e.maxLength;
if(e.value.length >= maxlen)
alert("Max length is limited to" +maxlen );
}
</script>
Using JQuery:
$("#inputFieldId").on("input propertychange", function(){
var val = this.value;
if(val.length > 15) {
this.value = val.substring(0,15); //comment if you don't want to remove the 16th character
alert("Maximum 15 characters allowed!");
}
});

Custom Error handling in js [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a form that takes students' information. On this form, there is an age entry with legal ages 8 to 20. If the age is less than 8 or greater than 20, a js alert pops up informing the student of the illegal age.
I am seeking for a way to create custom error handlers rather than just using the unfriendly js.alert() method. Any pointers to how this could be done will be appreciated.
To make error messages more user friendly here's one solution.
Create a div with no content. If an error is to be displayed, it will be displayed inside this div.
Here's how to do it with jQuery.
$('button').on('click', function() {
var value = $('input').val();
$('#error-message').html((value < 8 || value > 20) ? 'Error' : '');
});
#error-message {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='number' />
<button>Submit</button>
<div id='error-message'></div>
Here's a JavaScript solution
document.getElementById('submit').addEventListener('click', function() {
var age = document.querySelector('input').value;
var error = document.getElementById('error-message');
error.innerHTML = (age < 8 || age > 20) ? 'Error' : '';
});
#error-message {
color: red;
}
<input type='number' />
<button id='submit'>Submit</button>
<div id='error-message'></div>

Why does no DOM error appear when submitting my form using javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to generate an error message inside the page using DOM if the user does not enter details in the form field.
It is being sent to an external php file.
When I use Javascript I get the pop-up screen, but when I try using the DOM, to bring up the error, it just goes straight to the PHP file when the text field is blank.
Here is my js:
function validate(){
function namefield()
{
if (document.form.name.value == "")
{
document.getElementById("namef").innerHTML = "Please input name";
return false;
}
return true;
}
}
The html is simply:
<p id="namef"> some text</p>
<p>Name: <input type = "text" name = "name"> </p>
I highly recommend you to use jQuery or a proper JavaScript validator library for your form. Here is a simple example of how you can validate an input field with jQuery.
HTML part:
<input type="text" id="username">
<input type="button" id="sendForm" value="send">
<p id="usernameError"></p>
jQuery part:
$(function () {
$('#sendForm').on("click", function () {
validateUserForm();
});
});
function validateUserForm()
{
var username = $('#username').val();
if (username == '') {
$('#usernameError').html('Please insert your username!');
}
else {
$('#usernameError').html('');
}
}
And here is a functional jsFiddle: https://jsfiddle.net/1bk3ufhd/
If "formname" is the value of the name attribute of the form and "name" is the value of the name attribute of the input field (as per your example):
if( document.forms["formname"].elements["name"].value == "" ){
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
document.getElementById("namef").innerHTML = "Please imput name";
return false;
}

Explanation needed regarding JavaScript arrays and how they are being implemented [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have some JavaScript written by someone else and I'm trying to figure our exactly where some values are coming from, how they are formatted and what is being done with them. The values in question are citNumFirst, dateFirst, cdValues and cnValues.
This JavaScript is used to recursively open form fields for numbers and dates, then make an Ajax request (I think), but the Ajax data doesn't make any sense (value is: data: "countCitNum=" + countCitNum,)
Here is the code I need help with. Again, I'm trying to figure out where these values citNumFirst, dateFirst, cdValues and cnValues are coming from as these are what are being sent through the form submission (according to Fiddler).
My thinking is that this can all be done more efficiently with PHP, but I'm curious if the Ajax is even doing anything here, and if not are the values "cdValues" and "cnValues" being send as Javascript Arrays, or objects using the input forms.
$(document).ready(function() {
var citArray = [];
var thisCount = 1;
varcountCitNum = -1;
var cnArray = [];
var citNum = '';
var cnFirst = '';
var cdArray = [];
var issueDate = '';
$("#cnValues").val(cnArray);
$("#cdValues").val(cdArray);
function addCitNumber(){
var citNumField = document.getElementById("citNumFirst");
if(citNumField.value ==''){
var addfield_msg = "<span style='color:#F00;'>Please enter <br />Citation Number</span>";
$('#addfield_error').removeClass('hideCat');
$('#addfield_error').append(addfield_msg);
return false;
}else{
countCitNum++;
var addHTML = '';
var addDateHTML = ''
$.ajax({
type: "POST",
url: "/ci/ajaxCustom/addCitNum",
data: "countCitNum=" + countCitNum,
success: function(results){
if(results){
countCitNum = results;
}
addHTML = '<div id="newCitNum_'+countCitNum+'"><br /><strong>Citation Number:</strong><br /><input type="text" id="citNumInput_'+countCitNum+'" onchange="setCitNum(this,'+countCitNum+')"/></div>';
addDateHTML = '<div id="newDate_'+countCitNum+'"><br /><strong>Citation Issue Date:</strong><br /><input type="text" id="citDateInput_'+countCitNum+'" class="date" onchange="setIssueDate(this,'+countCitNum+')" readonly="readonly"/><img src="/euf/assets/themes/standard/images/delete_x.gif" width="29" height="23" border="0" class="imgDelete"/>Delete Citation Number</div>';
$('#anotherCitNum').append(addHTML);
$('#anotherCitDate').append(addDateHTML);
document.getElementById("#citDateInput_"+countCitNum);
$("#citDateInput_"+countCitNum).attr("disabled",true);
$(".date").datepicker();
}
});
}
data="";
}
*//******
Set Additional Citation Numbers and enable the date input
******/
function setCitNum(obj, countCitNum){
if(obj.value !='')
{
cnArray[countCitNum] = obj.value;
$("#cnValues").val(cnArray);
$("#citDateInput_"+countCitNum).removeAttr("disabled");
}else{
$('#citDateInput_'+countCitNum).val('');
$("#citDateInput_"+countCitNum).attr("disabled", true);
}
}
/******
Set Issue Date of additonal citations
******/
function setIssueDate(obj, countCitNum){
if(obj.value !=''){
cdArray[countCitNum] = obj.value;
}else{
cdArray[countCitNum] = '';
}
$("#cdValues").val(cdArray);
}
/******
Set Citation Number and enable date input unless Citation Number is blank
******/
function setFirstNum(obj){
cnFirst = obj.value;
$('#addLink').empty();
if(obj.value !='')
{
$("#citNumFirst").val(cnFirst);
$("#dateFirst").removeAttr("disabled");
$('#addfield_error').empty();
$('#addfield_error').addClass('hideCat');
var addLinkHTML = "<a href='javascript:void(0)' onclick='addCitNumber();'>Click here to add another Citation Number</a>"
$('#addLink').append(addLinkHTML);
}else{
$('#dateFirst').val('');
$("#dateFirst").attr("disabled", true);
}
}
/******
Set Issue Date of citation
******/
function setFirstDate(obj){
var issueDate = obj.value;
$("#dateFirst").val(issueDate);
}
Here is the associated HTML
<input type="hidden" name="cnValues" id="cnValues" />
<input type="hidden" name="cdValues" id="cdValues" />
<input type="text" id="citNumFirst" onblur="setFirstNum(this)" value=""/></div>
<div id="addfield_error" class="hideCat"></div>
</div>
<div id="anotherCitDate" style="float:left; padding-left:15px">
<input type="text" id="dateFirst" class="date" onchange="setFirstDate(this)" value="" readonly="readonly"/>
As far as I can tell, this is what's happening:
citNumFirst and dateFirst are the initial inputs. When citNumFirst input is changed (note: this definitely needs input validation), "Click here to add another" link appears. Clicking it will increment countCitNum, send that to the Ajax call, and if it's successful, display an additional set of date/number inputs which can be used to create a new citation number.
Ajax call: I'm not entirely sure what's going on here because what it's passing is the index of the input fields (countCitNum) that will be added (starting with zero and not counting the initial set). It's not passing the actual number or date, and it looks like it's expecting to receive that same index as results.
cnValues and cdValues store cnArray and cdArray, which are used to store the numbers and dates, respectively, of citations added using these newly created input fields. cnArray[0] corresponds to the value in input #newCitNum_0; cdArray[0] corresponds to #newDate_[0]. Any updates made to these input fields result in changes to the array, but I'm not seeing them being used anywhere in your code snippet (but since they are hidden inputs, they are probably being used after form submit).

Categories