variable assignment prevents from removing item? - javascript

I'm creating editable area, where normal text is replaced by input and you can edit values. After editing you can hit enter or click button to accept that. During editing edited variable is set to true to prevent other fields to be editable. Here's the HTML
<section class="person-info">
<div class="row">
<span id="name" class="editable">Martin Chikilian</span>
<span id="living-place" class="editable">Portland, Oregon, USA</span>
<span id="langs" class="editable">English, French, German</span>
</div>
</section>
and javascript code:
$(function(){
var edited = false;
$('.editable').click(function(){
if(!edited){
edited = true;
var _this = $(this);
var confirmIcon = (_this.attr('id') == 'name') ? 'big-confirm' : 'confirm';
var text = $(this).text();
//this will be injected into editable element to replace existing text
var input = $('<input type="text" value="' + text +'" /><span id="accept" class="icon ' + confirmIcon + '"></span>');
_this.html('');
_this.append(input);
input.focus();
var accept = _this.find('#accept');
//binding click event to confirmation button
accept.click(function(){
var inputVal = input.val();
_this.html(inputVal);
//edited = false;
});
//binding event to enter press
input.keypress(function(e){
if(e.which == 13){
var inputVal = input.val();
_this.html(inputVal);
edited = false;
}
});
}
});
});
Everything works when you hit enter, but when I try to do that by clicking acccept button it does nothing unless I remove variable assignment edited = false;. But it can't be left like that because it prevents other fields to be editable. What is the problem? Is it because element with event attached (accept button) is removed as well? Does anyone have any solution or clear explanation of that behavious? Thanks in advance!

Since #accept is a child of .editable, the click event that you're listening to bubbles up the DOM and the click handler on .editable is fired off too, causing edited === true.
You can get around this by stopping the event from propagating using event.stopPropagation():
accept.click(function(e){
var inputVal = input.val();
_this.html(inputVal);
edited = false;
e.stopPropagation();
});
Example: http://jsfiddle.net/6zAN7/13/

Related

Select textarea, focus it and simulate pressing a space bar

When user clicks on an img i want to add it's alt value into textarea and add a space to it as if user pressed it himself but not like this el.value += ' ';
Code :
var chatInput = document.querySelector('textarea[data-a-target="chat-input"]'); //textarea selector
var chatSend = document.querySelector('button[data-a-target="chat-send-button"]');
emoteList.addEventListener('click', function(e){
if(e.target.nodeName == 'IMG'){
chatInput.focus();
chatInput.value += e.target.alt;
}
})
The text gets added into textarea, but textarea change event doesn't fire.
What would be the best way to do this? I have spent hours using both Javascript and jQuery to make it work using events but i can't get it right.
I tried focusing on textarea and using dispatch/fire event on window but it does nothing.
I tried firing keypress on textarea but it has no effect either.
if your problem is that change event is not triggering then you can manually trigger it by
var e = $.Event( "change" );
$("#altArea").trigger(e);
Don't need jQuery for this - just use chatInput.dispatchEvent(new Event('change'));.
const chatInput = document.querySelector('textarea');
chatInput.addEventListener('change', () => {
console.log('saw a change');
})
const chatSend = document.querySelector('button');
document.querySelector('#emote-list').addEventListener('click', (e) => {
if(e.target.nodeName !== 'DIV') return;
chatInput.focus();
chatInput.value += 'foo ';
chatInput.dispatchEvent(new Event('change'));
})
<textarea></textarea>
<div id="emote-list">click</div>

Input loses placeholder after double-click

On click placeholder disappears, on blur it reappears, but if double-click happens instead of 1 click placeholder just disappears forever, turning off double-click default doesn't help either. Is it somehow possible to treat double-click as normal click? Or is it supposed to destroy placehoder?
var input = document.getElementsByTagName("input")[0];
input.onclick = function() {
p_holder = this.placeholder;
this.placeholder = "";
}
input.onblur = function() {
this.placeholder = p_holder;
}
input.ondblclick = function(e) {
e.preventDefault();
}
<input type="text" placeholder="text goes here">
I think this might be what you are looking for.
Comments are in the source code.
var input = document.getElementsByTagName("input")[0];
// Store original placeholder
var p_holder = input.placeholder;
// Remove on focus
input.onfocus = function() {
this.placeholder = "";
}
// Restore on blur
input.onblur = function() {
this.placeholder = p_holder;
}
<input type="text" placeholder="text goes here" />
If you have any questions please leave a comment below and I well get back to you as soon as possible.
I hope this helps. Happy coding!
It is not double click, but two single clicks which are causing this issue, because on the second click, the value of p_holder will be set to ''.
To prevent that, you can check for the value first:
input.onclick = function (){
if (this.placeholder !== '') {
p_holder = this.placeholder;
this.placeholder = "";
}
}
By the way, if you just need to deal with placeholder, you actually don't need to manipulate it. The browser automatically removes it when some value is inserted into the input, and restores it when the value is removed.

How to remove/disable submit on appendTo Elements?

I've created a function to focus the next input with the enter key and disabled the submit on the form. It works fine but when I add an input field with the appendTo function it will reactivate the submit function on my form. I want to focus the input fields with the enter key and not with tab key.
Here is my function:
$('input').keydown(function (e) {
if (e.which === 13) {
var index = $('input').index(this) + 1;
$('input').eq(index).focus().val("");
return false;
}
});
And my appendTo function
var inputs = $('<input type="text" name="inputBasic[]" value="" class="form-control" />');
inputs.appendTo($("#dc_step_inputs"));
How can I remove the submit function when I add dynamical input field?
Thanks you for an answer!
You are binding your keydown event handler to a static set of elements (which does not include any elements added dynamically after your event handler has been attached), use delegation to bind to any elements that show up under your form:
$('#parent-form-id').on('keydown', 'input', function(e){
if (e.which === 13) {
var index = $('input').index(this) + 1;
$('input').eq(index).focus().val("");
return false;
}
});
$('input') only affects the elements that exist at the time this function runs.
You need to run the same script on the inserted element(s) too:
var inputs = $('<input type="text" name="inputBasic[]" value="" class="form-control" />');
inputs.appendTo($("#dc_step_inputs"));
inputs.keydown(function (e) {
if (e.which === 13) {
var index = $('input').index(this) + 1;
$('input').eq(index).focus().val("");
return false;
}
});
you can name your key down function
$('input').keydown(keydown);
function keydown(){
if (e.which === 13) {
var index = $('input').index(this) + 1;
$('input').eq(index).focus().val("");
return false;
}
and when you create a new input, give it an id, like this:
var inputs = $('<input id="newInput" type="text" name="inputBasic[]" value="" class="form-control" />');
inputs.appendTo($("#dc_step_inputs"));
and then
$('#newInput').keyDown(keyDown);
As has already been mentioned, when you add an event listener to a DOM element in JavaScript, you set it again the element itself, rather than a selector, or a given collection of elements.
One way around this, is to add an event listener to a common parent of all the elements for which you wish your event to be triggered against. This process is called Event Delegation. Fortunately, in jQuery this is very simple, using the following syntax:
$(<parent_selector>).on(<event>, <child_selector>, <fn>);
From the example you provided this might look something like (presuming you only want to target inputs within #dc_step_inputs):
$("#dc_step_inputs").on("keydown", ":input", function(e) {
if (e.which === 13) {
var index = $('input').index(this) + 1;
$('input').eq(index).focus().val("");
e.preventDefault(); // Note, this is preferred to return False
}
});

Add value from radio button to existing link url use javascript

i have javascript script :
<script type="text/javascript">//<![CDATA[
window.onload=function(){
document.mainForm.onclick = function(){
var radVal = document.mainForm.pages.value;
result.innerHTML = 'You selected: '+radVal;
}
}//]]>
</script>
radio button :
<form id="mainForm" name="mainForm">
<input name="pages" type="radio" value="p1">
<input name="pages" type="radio" value="p2">
<input name="pages" type="radio" value="p3">
</form>
<span id="result"></span>
<a href="http://localhost/folder/blabla.php?p=book'>Book</a>
i want form click radio button the value from radio button has place on the link url, so that can be :
link : <a href='http://localhost/folder/blabla.php?p=book&o=p1'>Book</a>
add value &o=p1
can anyone help me?
thank you before
Your form doesn't need a name, it's superfluous. The way you've attached the listener, this within the function will reference the form so you can do:
window.onload=function(){
document.mainForm.onclick = function(event){
var radVal = this.rads.value;
// do stuff with radVal
}
For your solution, consider the following which adds the listener onload, then conditionally modifies the URL whenever there's a click inside the form. You could use a click event on each button, or look at the event and see if it came from one of the buttons, but I think it's simpler to just update the URL ever time there's a click:
window.onload = function() {
var form = document.forms['mainForm'];
if (form) {
form.addEventListener('click', function() {
var link = document.getElementById('a0');
// Note that if there is only one such button, this will return a
// reference to the single element so maybe querySelectorAll is better
var buttons = this.pages;
// var buttons = this.querySelectorAll('[name=pages]');
for (var i=0, iLen=buttons.length; i<iLen; i++) {
if (buttons[i].checked) {
// Add to the href or replace if previously added
link.href = link.href.replace(/\&.*|$/, '&o=' + buttons[i].value);
// debug
console.log(link.href);
// Stop once checked button is found
return;
}
}
}, false);
}
}

Javascript onblur/onfocus

I am having some trouble with the two events, they work fine, however I have ran into a problem:
I have a div inside of a div. When the inner div is in focus, I want a set of style buttons to be appended to the outer div. However when i try to click on the buttons, it unfocuses the inner div and makes the buttons go away. I want them to go away when focus is lost but I dont want focus to be lost when I press a button. Sorry if this is a little confusing here is some code and a jsfiddle of it in action:
function addButtons() {
var node = document.createElement('div');
var obj = document.getElementById('container');
node.setAttribute('id', 'buttons');
node.innerHTML = '<input type="button" value="B" onClick="document.execCommand(\'bold\',false)" />';
obj.appendChild(node);
}
function removeButtons(id) {
var obj = document.getElementById('container');
obj.removeChild(obj.childNodes[3]);
}
http://jsfiddle.net/bnjGE/2/
If I remove the removeButtons() function, it works fine, but multiple buttons will be created.
I can try to clear things up, just ask.
Thankyou
You can add a return false; statement on the mousedown event on the button, f.ex:
node.getElementsByTagName('input')[0].onmousedown = function(e) {
return false;
};
http://jsfiddle.net/bnjGE/8/
document.onclick = function(e){
console.log(e.target);
if(e.target.id != 'buttons' && e.target.parentNode.id != 'buttons' && e.target.id != 'textarea'){
removeButtons();
}
}​
http://jsfiddle.net/bnjGE/7/
Maybe this is a solution,but not perfect.

Categories