Issue on Targeting .prev() closest() Class of a Text Box - javascript

Can you please take a look at This Demo and let me know why I am not able to target the first .fa class before the text box #name ?
I am trying this:
$(this).prev().closest(".fa").addClass("err");
at this code
<div class="row">
<div class="col-md-3">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-user err-test">Name</i>
</div>
<input type="text" class="form-control form-input-gray" id="name" placeholder="Enter Your Name" />
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-default btn-block" id="btn-contact-rquest">Contact</button>
<br />
<div id="result"></div>
<script>
$(function () {
function txtInput(elem) {
var inputData = $.trim(elem.val());
if (inputData == "") {
$(this).prev().closest(".fa").addClass("err");
}
else{
return inputData;
}
}
$("#btn-contact-rquest").on("click", function (e) {
if (txtInput($('#name'))) {
$("#result").html("No Error");
} else {
$("#result").html("Error");
}
});
});
</script>
but cant target the .fa can you please let me know how to fix this?
Thanks,

From .closest() docs,For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree but in your case .fa is not ancestors of $('#name').
Instead of
$(this).prev().closest(".fa").addClass("err");
Try
elem.prev().children(".fa").addClass("err");
Working Demo

Try this: FIDDLE
$(elem).parent().find(".fa:eq(0)").addClass("err");

I think you miss reading the html.
Because before the input field, that is a div with class of input-group-addon.
Hence, your selector is incorrect.
I changed your JS to :
$(function () {
function txtInput(elem) {
var inputData = $(elem).val();
if (inputData != "") {
return inputData;
}
else{
$(".input-group").addClass("err");
}
}
$("#btn-contact-rquest").on("click", function (e) {
if (txtInput($('#name'))) {
$("#result").html("No Error");
} else {
$("#result").html("Error");
}
});
});
http://jsfiddle.net/fjm63j56/3/

Related

My disable submit if input empty is not working

my disable submit button if input is empty is not working. When i put an input, the submit button still not able to click, it is still disabled.
what is wrong here? btw, Im still learning..
<div class="input-group mb-2 mx-sm-2 my-sm-4">
<div class="form-outline">
<input type="search" id="" placeholder="North Borneo.." name="valueToSearch" class="form-control" />
</div>
<button type="submit" class="btn btn-primary" name="caribtn" disabled="disabled">
<i class="mdi mdi-magnify"></i>
</button>
</div>
$(function () {
$('.button[type="submit"]').keyup(function () {
var empty = false;
$('.input[type="search"]').each(function () {
if ($(this).val().length == 0) {
empty = true;
}
});
if (empty) {
$('.button[type="submit"]').attr("disabled", "disabled");
} else {
$('.input[type="search"]').removeAttr("disabled");
}
});
});
Try it.
$(function() {
var btnSubmit = $('button[type="submit"]');
btnSubmit.attr('disabled', 'disabled');
$('input[name="valueToSearch"]').on('keyup', function() {
if ($(this).val() !== '') {
btnSubmit.removeAttr('disabled');
} else {
btnSubmit.attr('disabled', 'disabled');
}
})
});
.button or .input class doesn't exist in your context.
Attach a handler to all your search inputs; and inside check if any of them are empty.
$(function() {
$('input[type="search"]').keyup(function() {
var empty = false;
$('input[type="search"]').each(function() {
if($(this).val().length === 0) {
empty = true;
}
});
if (empty) {
$('button[type="submit"]').attr('disabled', 'disabled');
} else {
$('button[type="submit"]').removeAttr('disabled');
}
});
});
.mdi-magnify::before {content: "magnify-icon";display:inline-block;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group mb-2 mx-sm-2 my-sm-4">
<div class="form-outline">
<input type="search" id="" placeholder="North Borneo.." name="valueToSearch" class="form-control" />
</div>
<button type="submit" class="btn btn-primary" name="caribtn" disabled="disabled">
<i class="mdi mdi-magnify"></i>
</button>
</div>

duplicate and clone div

sorry i do not speak english well, i want to create a tool that allows to duplicate a div thanks to an "input number" and a button and then I also want to clone this tool by reinitializing it to be able to use the tool again , Here is a piece of code:
$(function() {
$('#btn_dupliquate').on('click', function() {
var numDuplication = $('#num-duplication').val();
if (numDuplication > -1) {
var div = $('.common_preview');
$('.result').html('');
for (var i = 0; i < numDuplication; i++) {
$('.result').append(div.clone());
}
}
});
});
$(function() {
$(".heading").keyup(function() {
var heading=$(this).val();
$(".common_preview").html("<div class='bloc'><p class='model'>"+heading+"</p></div>");
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toNumDuplicate">
<input type="text" class="heading" />
<br/>
<br/>
<input id="num-duplication" type="number" >
<br/>
<br/>
<button id="btn_dupliquate"> dupliquate </button>
</div>
<div id="toDuplicate">
<div class="common_preview" >
<div class="bloc">
<p class="model">test</p>
</div>
</div>
</div>
<div class="result"></div>
<button id="btn_clone">clone</button>
You could abstract your function to take dynamic selector strings for the duplicate button, duplicate number input, preview div and result div.

Issue on Checking Multi Inputs Calculation Using each()

Can you please take a look at this Demo and let me know why I am not able to do the calculation check using the each iterator?
As you can see I tried to use :
if (!parseInt($(this).val()) === ((parseInt($(this).closest('div').find('.upper').text())) - parseInt($(this).closest('div').find('.lower').text()))) {}
Which it didnt work then I used this :
if (!parseInt($(this).val()) === ((parseInt($(this).prev('.upper').text())) - parseInt($(this).prev('.lower').text()))) {
but still not validating the input?
I'm not sure if that what you want to achieve, take a look at following example :
$('#test').on('click', function (e) {
$("input").each(function () {
if ($(this).val().length === 0)
{
$(this).addClass('input-error');
} else {
var upper = parseInt($(this).prev().prev().text());
var lower = parseInt($(this).prev().text());
var current_value = parseInt($(this).val());
if (current_value != (upper-lower)){
$(this).addClass('input-error');
}else{
$(this).removeClass('input-error');
}
}
});
});
.input-error {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper">5</div>
<div class="lower">2</div>
<input type="text" id="txt1">
<hr />
<div class="upper">7</div>
<div class="lower">3</div>
<input type="text" id="txt2">
<hr />
<div class="upper">200</div>
<div class="lower">66</div>
<input type="text" id="txt3">
<hr />
<br />
<button type='button' id="test">Test</button>

Cannot make simple jQuery work

I'm learning jQuery, but I can't make this example work. I know it's quite simple but I don't know what I'm missing. I'm trying to add the class "invalid" in a textfield.
<script src="../jquery/jquery-1.8.2.js"></script>
<script src="../jquery/jquery.ui.effect.js"></script>
<script>
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
return false;
}
});
</script>
<main>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</form>
</main>
There is a syntax error in your Javascript. The corrected Javascript:
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
return false;
}
});
});
Fiddle here: https://jsfiddle.net/s9x1Ldfm/
However I would add the return does not make a lot of sense. It returns false sometimes and void others. What exactly are you trying to do with that?
So, the problem in your code is that you are missing some closing ')' and '}'. The following will make it correct:
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
} // end of for
return false;
} // end of if
}); // end of click
});
You can try to debug your javascript by using the debugger in the browser, by clicking F12. In the Element/Console section, you can see the error messages you have in your code. It will give you some hints regarding the error you have. Also, if you do not have any syntax problem, you are able to use
debugger;
In your code and when you run it in your browser with the debugger mode (F12), you can debug step by step into your code and look at the values of the variables and see how your program is behaving.
But, if in your code you just want to see if the input text is empty or not by the time the user click the button, you can try the following snippet:
<script>
$(function() {
$('#create_task').on('click', function() {
event.preventDefault(); // prevents submission
if ($('.validate').val().length > 0) {
$('.invalid').hide();
} else {
$('.invalid').show();
}// end of if
}); // end of click
});
</script>
<main>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<div class="invalid" style="display:none">Invalid input</div>
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button id="create_task" class="btn" type="submit" name="createTask">Create Task</button>
</form>
</main>
Pay attention how I changed the name of button to id to detect the button without extra validation. I hope it helps.
Use event.preventDefault() to prevent the form submission.
Check out his fiddle.
Here is the snippet.
$('button.btn').click(function(event) {
event.preventDefault();
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
});
.invalid {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate" />
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</form>
Your code has number of issues. First of all, if you want to capture form submission use .submit function and not click on button. Otherwise, you can remove the form tag and capture the click on button element.
Additionally, you can loop through jQuery object using .each. Using for is definitely faster as it is a native JavaScript functionality. I have made a proof of concept on this jsfiddle.
See this code.
$(function () {
$('button.btn').on('click', function () {
if ('create_task' == $(this).val()) {
$('.validate').each(function (i, e) {
if ("" == $(e).val()) {
$('.validate').addClass('invalid');
} else {
$('.validate').removeClass('invalid');
}
})
}
})
});
.invalid
{
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</main>
You have a syntax error as you haven't closed the $(function(){ in your script.
Moreover move your return false to an outer block (so that you'll prevent the default submit behaviour of the button) AND, use submit (which is same as using .submit() method) event as such:
$(function() {
$('button.btn').on('submit', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
return false;
});
});
NOTE: If you wanted, you could change the type='submit' to type='button' while triggering the click event, thus ridding you of returning false in your JavaScript code.

Show div when textbox value is same as another div's content

I am making a quiz in which the answer will be random. I want the "Correct!" div to show when the textbox value is the same as another div.
Here's what I've got so far:
$(document).ready(function(){
$("#buttontest").click(function(){
if ($('#full_day').val() == '#answer') {
$("#correct").show("fast"); //Slide Down Effect
}
else {
$("#correct").hide("fast"); //Slide Up Effect
$("#incorrect").show("500").delay("1000").hide("500");
}
});
});
<p>What is the animal?</p>
<div id="correct">
That's Correct!
</div>
<div id="incorrect">
Sorry, Try again!
</div>
<div id="answer">Monkey</div>
<input type='text' id="full_day"/>
<input type='button' id="buttontest" value="clickme"/>
Use
$('#answer').text()
instead of just
'#answer'
in the if statement.
if ($('#full_day').val() == $('#answer').text())
This is case sensitive. To make it case insensitive:
if ($('#full_day').val().toLowerCase() == $('#answer').text().toLowerCase())
Edit: As requested, here is a solution which allows multiple answers:
$('#check').bind('click', function() {
var possibleAnswers = $('#answers').text().toLowerCase().split(' ');
var givenAnswer = $('#user-answer').val().toLowerCase();
var isAnswerCorrect = false;
for (var indexPossibleAnswers = 0; indexPossibleAnswers < possibleAnswers.length; indexPossibleAnswers++)
{
if (possibleAnswers[indexPossibleAnswers] == givenAnswer)
{
isAnswerCorrect = true
break;
}
}
if (isAnswerCorrect)
{
alert('Correct');
}
else
{
alert('Incorrect, try again.');
}
});
Live demonstration.
$(document).ready(function(){
$("#buttontest").click(function(){
if ($('#full_day').val() == $('#answer').html()) {
$("#correct").show("fast"); //Slide Down Effect
}
else {
$("#correct").hide("fast"); //Slide Up Effect
$("#incorrect").show("500").delay("1000").hide("500");
}
});
});
<p>What is the animal?</p>
<div id="correct" style="display:none;">
That's Correct!
</div>
<div id="incorrect" style="display:none;">
Sorry, Try again!
</div>
<div id="answer" style="display:none;">Monkey</div>
<input type='text' id="full_day"/>
<input type='button' id="buttontest" value="clickme"/>

Categories