Append and remove not working as they should - javascript

For some weird reason, my append is only adding but not removing.
Here is the HTML:
<div class="insert-links"></div>
<a href="#" id="button" onclick="return false;">
<img src="http://a.dryicons.com/images/icon_sets/blue_extended_icons_set/png/64x64/add.png" ">
</a>
and the jQuery is the following:
<script type='text/javascript'>//<![CDATA[
$(function() {
var i = 0;
$('#button').click(function() {
if (i < 10) {
$('.insert-links').append('<p style="display: none;" class="new-link"><input tabindex="1" placeholder="Command eg: give #user# 264" style="width:285px\;margin-top: 12px\;" type="text" name="fname" id="fname"/> <input tabindex="1" placeholder="Price" style="width:45px\;background-color:#f4faff\;" title="Price in points of this item" type="text" name="fname" id="fname"/><img src="http://c.dryicons.com/images/icon_sets/blue_extended_icons_set/png/128x128/remove.png" style="width: 20px;float: right;margin-top: 19px;margin-right: 19px;"></p>');
$('.insert-links').find(".new-link:last").slideDown("slow");
i++;
}
});
$('#buttonremove').click(function() {
if (i > 0) {
$('#buttonremove').parent('p').remove();
i--;
}
});
});//]]>
</script>
Could anyone please help me?

Use jQuery Event Delegation for this:
Fiddle Demo
$('.insert-links').on('click', '#buttonremove', function() {
if (i > 0) {
$('#buttonremove').parent('p').remove();
i--;
}
});

The problem is that you are binding the click event to the "buttonremove" when the page is loading , in that specific moment the paragraph containing all other elements does not exists yet. What you have to do is to move the binding code inside the click of the #button.

Related

JS Auto select next input and detect last input

Im trying to auto jump to the next input once keypress is triggered but my code isnt working and I believe its todo with the next() select but can't seem to get it selected correctly.
HTML Form
<form method="POST" action="">
<div id="confirm-input">
#csrf
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
<div class="col-xs-1">
<input type="text" class="form-control input" maxlength="1"/>
</div>
</div>
</form>
JS Code
$('.input').keyup(function (e) {
if (this.value.length == this.maxLength) {
var next = $(this).nextAll('input').first();
//Check if there is a next input.
if (next.length) {
next.focus();
} else {
$(this).blur
//AJAX CALL
}
}
});
Im using nextAll() as i believe it can look outside the div but not having any luck.
"Im using nextAll() as i believe it can look outside the div but not having any luck."
That's your problem right there. nextAll() only looks on the same tree level in the DOM. (Plunker here to demonstrate: http://plnkr.co/edit/u5t2Oy636xvl82WIgmvp?p=preview)
One possible solution would be to give your inputs successive ids, so that if your current input has an id of, say, "input-2", the look for "input-3" as the next input to focus on.
Update:
Here's a working Plunker that illustrates the above idea: http://plnkr.co/edit/UT5HydtxzyxkTIt5LBeZ?p=preview
$('.input').keyup(function (e) {
if (this.value.length == this.maxLength) {
var currId = $(this).attr('id');
var nextId = '#input-' + (Number(currId.split('-')[1]) + 1);
var next = $(nextId);
//Check if there is a next input.
if (next.length) {
next.focus();
} else {
$(this).blur
//AJAX CALL
}
}
}
My suggested solution is to determine how many elements match the selector then invoke .focus() using the index of each element, .blur() on the last element. You probably don't want to fire the AJAX call unless you've hit maxLength, hence the else if statement rather than just else.
var selector = "#confirm-input .input";
$(selector).keyup(function (e) {
var i = $(this).index(selector);
var len = $(selector).length - 1;
if (this.value.length == this.maxLength && i < len) {
$(selector).eq(i+1).focus();
}
else if(this.value.length == this.maxLength && i === len) {
$(this).blur();
//AJAX CALL
}
});

jQuery Field Not Being Removed After Appending it

I am running into an issue where I can't seem to get my jQuery script to remove fields after they have been added. I have tried a few changes, but nothing has worked.
$(function() {
var dataSourceField = $('#sign-up-organization-discovery-source');
var i = $('#sign-up-organization-discovery-source p').size() + 1;
$('#sign-up-add-discovery-source').on('click', function() {
$('<p><label for="discovery-source-field"><input type="text" id="discovery-source-field" size="20" name="discoverySource" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(dataSourceField);
i++;
return false;
});
$('#remScnt').on('click', function() {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<form action="/app/sign-up/organization" method="post">
<p>{{user.email}}</p>
<input type="hidden" name="admin" value="{{user.email}}">
<input type="hidden" name="organizationId">
<label for="sign-up-organization">Company/Organization Name</label>
<input type="text" class="form-control" id="sign-up-organization" name="organizationName" value="" placeholder="Company/Organization">
Add Another Discovery Source
<div id="sign-up-organization-discovery-source">
<input type="text" id="discovery-source-field" placeholder="Discovery Source" name="discoverySource">
</div>
<br />
<button type="submit">Submit</button>
</form>
Already have an account? Login here!
</div>
</div>
There are a couple problems here.
Firstly, an id is suppose to be unique! You are duplicating id attribute values each time you append the element.
Secondly, even if you were to use a class rather than an id, it still wouldn't work as expected because the clickable/removable a element doesn't exist in the DOM when you are attaching the event listeners.
You would either need to attach the event after appending the element, or you could use event delegation and attach the event to a common parent element that exists at the time.
Example Here
$('#sign-up-organization-discovery-source').on('click', '.remove', function() {
// ...
});
I changed Remove to: Remove.
Then I delegated the click event to the #sign-up-organization-discovery-source element.
$('##sign-up-organization-discovery-source').on('click', '#remScnt', function() {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});

Disabled button on click with jquery mobile

html:
<script src="http://zurb.com/playground/javascripts/plugins/jquery.textchange.min.js"></script>
<form>
<input type="text" name="comment" id="comment" placeholder="Comment" maxlength="140" value=""/>
<div id="charactersLeft"></div>
<input type="submit" id="commentButton" data-icon="edit" data-inline="true" data-mini="true" data-theme="b" value="Send" disabled="disabled"/>
</form>
<div id="actionList">
</div>
js:
$('#comment').bind('hastext', function () {
$('#commentButton').button('enable');
});
$('#comment').bind('notext', function () {
$('#commentButton').button('disable');
});
$('#comment').bind('textchange', function (event, previousText) {
$('#charactersLeft').html( 140 - parseInt($(this).val().length) );
});
$('#commentButton').click(
function(){
$('#actionList').prepend('<p class="item">' + $('input[name=comment]').val().trim() + '</p>');
$('#commentForm').each (function(){ this.reset(); });
//document.getElementById('commentForm').reset();
$(this).button('disable');
}
);
On Fiddle its works another, that on my machine. So, test local. The problem is: when I write a comment, than I click on the button, comment apears in #actionList, the button blocked. Nice. But. If I want to write a new comment, the button will be disabled. I have text in input, but I cant click button. I deleted my new text in input, and than I can write something and button finally enabled.
Its very strange, how to fix it? Thanks.
I added the line, to remove comment once posted:
$('#comment').val("");
I also replaced your hastext and notext functions with this code, added in the textchange function:
var tb_value = this.value;
if (tb_value == "") {
$('#commentButton').button('disable');
} else {
$('#commentButton').button('enable');
}
See the Fiddle.

Jquery append() doesn't work on new <a>Add</a>

Append() working fine but it is working only on the first <a class="add">Add</a>. not able to add new input field with the latest <a class="add">Add</a>
Here is my code
$(document).ready(function(){
var scntDiv = $('#add_words');
$('.add').click(function() {
$("#add_words").append('<div class="line">Word is <input type="text" /><a class="add">Add</a></div>');
return false;
});
});
html code
<div id="add_words">
<div class="line">Word is 1<input class="input1" type="text" value="1" /><a class="add">Add</a></div>
</div>
That's because click only attaches the click event handler to existing DOM elements, not future ones. You need jQuery on:
$(document).ready(function() {
$("#add_words").on("click", ".add", function(e) {
// Do your append here
// e.delegateTarget is your <div id="add_words">
$(e.delegateTarget).append('<div class="line">Word is <input type="text" /><a class="add">Add</a></div>');
// Prevent default action (e.g. don't follow links)
e.preventDefault();
});
});
Use on() for event delegation instead of click():
$('#add_words').on('click', '.add', function(){
$("#add_words").append('<div class="line">Word is <input type="text" /><a class="add">Add</a></div>');
});
use Live like this: see this jsfiddle
$('.add').live("click", function(event) {
$("#add_words").append('<div class="line">Word is <input type="text" /><a class="add">Add</a></div>');
return false;
});

Javascript onfocus / onblur issues

So I am making a little searchbar that shows results underneath of it like such:
<div id='searchWrapper'>
<div id='Search'>
<input id="inputSpn" type="input" value="" />
<input id="searchBtn" type="image" src="/search.png" />
<br clear='all'/>
</div>
<div id='Results'>
</div>
</div>
I am basically doing a livesearch with through AJAX. The <div id='Results'> is initially hidden until you type and it populates some results. My issue however is getting it to hide when the user clicks away. having it disappear through onblur does not work either as I need to be able to click on the results and not have them disappear on me. Unfortunately I have not been able to find a good non jQuery method on the internet yet. Simplest way to put it is: I want the results to disappear if anything but the <div id='searchWrapper'> is clicked. Thanks!
Here is a non-optimised but working non-jQuery solution
<script>
document.onclick=function(e) {
var elem = e?e.target:event.srcElement;
var id = elem.id;
document.getElementById("inputSpn").value=id+" clicked"; // debug - remove when happy
// the following could be done by looping over the searchWrapper and its children
if (id !="searchWrapper" && id!="Search" && id != "inputSpn" && id != "searchBtn" && id != "Results") {
document.getElementById("Results").style.display="none"
}
}
</script>
<div id='searchWrapper'>
<div id='Search'>
<input id="inputSpn" type="input" value="" />
<input id="searchBtn" type="image" src="TekTP/icons/search.png" />
<br clear='all'/>
</div>
<div id='Results'>hello
</div>
</div>
UPDATE:
Toggle if clicked on the wrapper div
var hide= (id !="searchWrapper" && id!="Search" && id != "inputSpn" && id != "searchBtn" && id != "Results");
document.getElementById("Results").style.display=(hide)?"none":"block";
Add a listener to the document (using addEventListener) - JSFiddle Example
<style>
#Results {
display: none;
}
</style>
<script type="text/javascript">
window.onload = function(){
document.addEventListener('click', function(event){
if(document.getElementById('searchBtn') != (event.target) ? event.target : event.srcElement) {
document.getElementById('Results').style.display = 'none';
} else {
document.getElementById('Results').style.display = 'block';
}
});
};
</script>
<div id='searchWrapper'>
<div id='Search'>
<input id="inputSpn" type="input" value="" />
<input id="searchBtn" type="button" value="Search"/>
<br clear='all'/>
</div>
<div id='Results'></div>
</div>
But if you are going to be using a significant amount of Javascript in your site, you might consider using jQuery - it will make your life much easier.

Categories