When I press the Submit button if any error is generated then code create a span element.
My question is how I can clear the old error from the error container element, or if not possible then please sum up the errors.
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span style="color: red;">'+error[0]+'</span>'));
});
I tried remove() but I cannot do it.
Thanks
you can remove the span with next().
next() finds the next sibling to the input field you are referring to.
it will give you the span:
el.next().remove();
you can use a class on the span f.e. class="validation-span"
el.next(".validation-span").remove();
this will make sure you only remove the span and no other element if existent :)
Add an span element after the input and set its HTML each time instead of using .after.
<input name="yourName">
<span class="errors"></span>
<script>
$(document).find('[name="'+i+'"] + .errors')
.html('<span style="color: red;">'+error[0]+'</span>');
</script>
I updated the both way you want, please pick which is more suitable to you
function logErrorCleanSpan(errorMessage){
$('#errorContainer').text(errorMessage);
}
logErrorCleanSpan("Hello");
logErrorCleanSpan("Jarvis");
function logErrorAppendSpan(errorMessage){
var span = $("<span>"+errorMessage+"</span>");
$('#errorContainerSpanAppend').append(span);
}
logErrorAppendSpan("1. Hello ");
logErrorAppendSpan("2. Jarvis ");
#errorContainerSpanAppend{
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Append Error and clean the previous error<h3>
<span id="errorContainer"></span>
<h3>Append Error and keep the older one<h3>
<span id="errorContainerSpanAppend"></span>
Assign a id with index to span after each click remove previous span using id
Use jquery remove
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span id="error'+i+'" style="color: red;">'+error[0]+'</span>'));
if($(document).find('span#error+i - 1+')) {
$( "span#error+i - 1+" ).remove();
}
});
this is just an example code not correct code.
Related
I have the following button link:
×
And the following js:
function reEnableBtn(prodId) {
alert(prodId);
};
Until now all good, on click of the link I get an alert with the content: 573 as expected.
Next thing I want to do is with the following html:
<a href="/new-page/?add-to-cart=573" class="button product_type_simple add_to_cart_button ajax_add_to_cart added" data-product_id="573">
<i class="fa fa-shopping-cart finished disabled-button"></i>
</a>
Within the JS I want to add a removeClass function which removes the classes 'finished' and 'disabled-button' from the <i> where the data-product_id of the parent <a> matches the value of prodId within the JS function (because I have other links with same structure but different data-product_id).
How do I do this?
You can
1) use attribute equal selector to target anchor element with same data product id
2) find element i in above anchor element
3) use removeClass to remove multiple classes from it
function reEnableBtn(prodId) {
$('[data-product_id=' + prodId + '] i').removeClass("finished disabled-button");
}
function reEnableBtn(prodId) {
$("a[data-product_id='"+prodId+"']").find("i").removeClass("finished disabled-button");
};
Use this simple script.
Use this code
jQuery(function($){
var s = $("body").find('[data-product_id=573]');
s.on("click", function(e){
var i = $(this).find('i');
if (i.hasClass('finished'))
i.removeClass('finished');
if (i.hasClass('disabled-button'))
i.removeClass('disabled-button');
alert("The classes was removed.");
return false; // this is for disabling anchor tag href
});
})
jsfiddle
If you have any other question feel free to ask in comments.
Fiddle
I am trying to clone a span from the onClick() function of a button. First time this works fine but when I try second time it is not cloning. What am I doing wrong?
Here is the essence of my code.
$(document).ready(function(){
$('.addmachinerow').on('click',function(){
var edcname = $('.edc_name option:selected').val();
var machine_description = $("input[name='machine_description'").val();
var capacity = $("input[name='capacity'").val();
var voltage_level = $("input[name='voltage_level'").val();
var powertype = $("select[name='typeofpower'").val();
var edcautovalue = $('.ecaddingspan').attr('data-value');
//if($('#bank_increment').html() == '') $('#bank_increment').html('0'); else $('#bank_increment').html(parseInt($('#bank_increment').html())+1);
//if($('#bank_clickededit').html() == '') var bank_increment = $('#bank_increment').html(); else var bank_increment = $('#bank_clickededit').html();
$('.ecaddingspan').clone().appendTo('.edcparent');
//$('.bankname, .bankbranch , .IFSCcode , .bankaccno , .accsincefrom').val('');
var edc_details = {'edcname' : edcname, 'machine_description' : machine_description, 'capacity' : capacity, 'voltage_level' : voltage_level, 'powertype' : powertype }
//$('.bank_details_array').append(JSON.stringify(bank_details)+'&&');
});
});
Additionally:
How can i clone the entire sets on clicking the Total clone button ?
I need to save the values in array with different names. Is that possible ?
How can i clone the entire sets on clicking the Total clone button ?
You've to use event delagtion on() instead :
$('body').on('click','.addmachinerow', function(){
//Event code
})
Since the new .addmachinerow added to the page dynamically after the clone.
I need to save the values in array with different names is that possible ?
I suggest the use of the array name [] like :
<input name='machine_description[]' />
<input name='voltage_level[]' />
Hope this helps.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$('.cloneitem').not('.cloned').clone().addClass('cloned').appendTo('body');
});
});
</script>
</head>
<body>
<p class="cloneitem">This is a paragraph.</p>
<button>Clone all p elements, and append them to the body element</button>
</body>
</html>
The issue is a common misconception of JQuery selectors. If you play with ID selectors then switch to class selectors then you often don't notice a difference in behaviour. The ID selector doc says
ID Selector: If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM
whilst for the class selector
Class Selector: Selects all elements with the given class.
What this means is that when you clone the target element you get away with a subsequent ID selection (JQuery ignores the duplicates) but a subsequent class selection will trip you up if you were not expecting JQuery to return multiple matches. Class selectors are great for grouping elements but not so great for cloning.
While I am on the soap box - whenever you use the clone function you should consider and fix the potential duplicate ID and un-required class duplicates that you are producing. Duplicate ID's are definitely bad show - duplicate classes may actually be by design but you should still consider them.
In the code sample below I assign the class iAmSpartacus to the original span which the onClick() function then clones. Each clone also gets the iAmSpartacus class so I remove it from each new clone to ensure that the $(".iAmSpartacus") selector always returns a maximum of one element. The spans show their current class property to prove the point.
// this runs one - shows us classes of original span
var origSpan=$(".iAmSpartacus")
origSpan.html("My classes are: " + origSpan.prop("class"))
$("#daButton").on("click", function(e) {
var newSpan = $(".iAmSpartacus").clone();
newSpan.removeClass("iAmSpartacus"); // remove the dup targetting class
newSpan.appendTo('.edcparent');
newSpan.html("My classes are: " + newSpan.prop("class"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="daButton">Click me</button>
<div class="edcparent" style="border: 1px solid red;">
<span class="ecaddingspan iAmSpartacus" style="display: block;">I am a span</span>
</div>
I'm having trouble applying class to the previous element or the next element.
<a href="#"><span class="glyphicon glyphicon-thumbs-up up"></span>
<a href="#"><span class="glyphicon glyphicon-thumbs-down down"></span>
I want to disable the second span, when I click the first span and vice versa.
$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
var down = $(this).parent().nextAll('a.comment-vote-down');
down.removeClass('disable-link').addClass('disable-link');
}else if($(this).hasClass('down')){
var up = $(this).parent().prevAll('a.comment-vote-up');
up.removeClass('disable-link').addClass('disable-link');
}
});
example on jsfiddle
You try to find class .comment-vote-down that doesn't exist in your HTML code
https://jsfiddle.net/xnovq390/4/
try this:
$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
var down = $(".down");
down.removeClass('disable-link').addClass('disable-link');
}else if($(this).hasClass('down')){
var up = $(".up");
up.removeClass('disable-link').addClass('disable-link');
}
});
It's because you don't have an a with a class of .comment-vote-down, or comment-vote-up.
Either take that part out of your nextAll selection:
.nextAll('a');
https://jsfiddle.net/xnovq390/1/
or, add in the class to your HTML:
<a href="#" class="comment-vote-up">
https://jsfiddle.net/xnovq390/3/
If the .up element is always the previous element from the .down one, you can simply do:
$(document).on('click', '.up, .down', function(e) {
e.preventDefault();
if ($(this).hasClass('up')) $(this).next().addClass('disable-link');
else $(this).prev().addClass('disable-link');
}
$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
$(this).addClass('disable-link');
$('span.down').removeClass('disable-link');
}else if($(this).hasClass('down')){
$(this).addClass('disable-link');
$('span.up').removeClass('disable-link');
}
});
As the other answers already stated, there is no spoon element with .comment-vote-down class.
But additionally to make life easier, you could buffer the 2 elements, bind the click to them and disable the ones not clicked, reducing the code to
var btns = $('.up, .down');
btns.click(function(){
btns.not(this).addClass('disable-link');
});
fiddle
If you'd want to disable the containing a, the 'other's parent could be obtained by chaining parent() : btns.not(this).parent().addClass('disable-link'); ( or .closest('a') if there is a deeper hierarchy)
I have this code
<span></span>
and this
<div> variable like a number </div>
and
<script>
$(document).ready(function(){
var x = $('div').html();
$('span').html(x)
});
</script>
I need that every time I change the div value, the span reflects the changes of the div
For example.
If I type 1 in the div, the span should immediately show me number 1
If I type 3283 in the div, the span should immediately show me number 3283
but with this code - I need to create
$("div").click(function(){
var x = $('div').html();
$('span').html(x)
});
I do not want to use .click(function) . in need this function run Automatically
after your answer
I use this code
http://jsfiddle.net/Danin_Na/uuo8yht1/3/
but doesn't work . whats the problem ?
This is very simple. If you add the contenteditable attribute to the div, you can use the keyup event:
var div = $('div'),
span = $('span');
span.html(div.html());
div.on('keyup', function() {
span.html(div.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span></span>
<div contenteditable="true"> variable like a number </div>
here is a demo with input:
html:
<span></span>
<input type="text" id="input01">
js:
$(document).ready(function(){
$( "#input01" ).on('keyup',function() {
var x = parseFloat($('#input01').val());
$('span').html(x)
});
});
How can you edit in div element on browser?
It have to be any input type then only you can edit or change value.
So for that on click of that div you have to show some input/textarea at that place and on change event of that input you can update the value of input in span.
<div id="main-div">
<input type="text" id="input-box" />
</div>
<script>
$(document).ready(function(){
$('#input-box').change(function(){
$('span').html($(this).text)
});
});
</script>
$("input[type=text]").change(function(){
var x = $('div').html();
$('span').text(x)
});
This can be use with textbox or textarea, For div user cannot enter text.
http://jsfiddle.net/uuo8yht1/
.change() will not work with a DIV-element. Since you did not specify how the DIV is updated I would recommend either setting a timer or using .keypress()
Example with timer:
$(function(){
var oldVal = "";
var divEl = $("div");
setInterval(function(){
var elTxt = divEl.text();
if (elTxt != oldVal) {
oldVal = elTxt;
$("span").text(elTxt);
}
}, 50);
});
You need a key listener, jquery provides a .keypress(), Examples are provided on keypress documentation.
I recommend to lookup the combination of .on() and .keyup() with some delay or throttle/debounce either via jquery or underscore.js library.
One of the reason or need for delay is to prevent too many event calls which will affect performance.
Here is an example of code in another question regarding throttle and keyup
Hope this helps.
I have got a lot of span tags inside my div elements. Each div has a unique id.I want to add an onclick event to the span elements in each div uniquley. How can i do that?
<div class="bootstrap-tagsinput"id="1">
<span class="tag label label-info">Access control lists</span>
<span class="tag label label-info">Network firewall</span>
</div>
<div class="bootstrap-tagsinput"id="2">
<span class="tag label label-info">Access control lists</span>
<span class="tag label label-info">Network firewall</span>
</div>
My current script which catches all the span elements irrespective of the div.
$('span.label-info').click(function() {
var news=$('input[type=text][id="vuln<?php echo $model->v_id;?>"]').val()+','+$(this).text();
$('input[type=text][id="vuln<?php echo $model->v_id;?>"]').val(news);
return false;
});
How can i catch click on span elements inside each div separately?
I think you're looking at it the wrong way. Instead of having a separate click handler for each div, you can keep the shared click handler, but find out which div is the parent, and use its ID in the subsequent selectors.
$('span.label-info').click(function() {
// find the parent/ansector that is a div and has the class
var divId = $(this).closest('div.bootstrap-tagsinput').prop('id');
var news=$('input[type=text][id="vuln' + divId + '"]').val()+','+$(this).text();
$('input[type=text][id="vuln' + divId + '"]').val(news);
return false;
});
Your code should work to add a click even handler to each span.
$('span.label-info').click(function() {
$(this).attr('id'); //<--$(this) is a handle to the clicked span
$(this).parent().attr('id'); //<-- $(this).parent() references the parent div
});
It's worth mentioning, consider changing .click() to .on('click').
Also - if you wanted to bind once without rebinding after spans were dynamically added to the div, you could bind it like this:
$('div').on('click', 'span.label-info').click(function() {
/* <-- do stuff with $(this) or $(this).parent() here --> */
});
http://jsfiddle.net/GZVdL/3/
Hi.
in your span click event you can find parent div and then get its attribute id to find which div it is.
Below is the code
$(document).ready(function(){
$(".tag").click(function(){
alert($(this).parent().attr("id"));
});
});