I would like to change text to input text by clicking on it :
Currently I've:
<div class="wrapper">
<span class="text-content">Double Click On Me!</span>
</div>
And in javascript:
//plugin to make any element text editable
$.fn.extend({
editable: function () {
$(this).each(function () {
var $el = $(this),
$edittextbox = $('<input type="text"></input>').css('min-width', $el.width()),
submitChanges = function () {
if ($edittextbox.val() !== '') {
$el.html($edittextbox.val());
$el.show();
$el.trigger('editsubmit', [$el.html()]);
$(document).unbind('click', submitChanges);
$edittextbox.detach();
}
},
tempVal;
$edittextbox.click(function (event) {
event.stopPropagation();
});
$el.dblclick(function (e) {
tempVal = $el.html();
$edittextbox.val(tempVal).insertBefore(this)
.bind('keypress', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
submitChanges();
}
}).select();
$el.hide();
$(document).click(submitChanges);
});
});
return this;
}
});
//implement plugin
$('.text-content').editable().on('editsubmit', function (event, val) {
console.log('text changed to ' + val);
});
But I don't know how to change double click on simple click ! I've tried to replace $el.dblclick(...) by $el.click(), but it doesn't work.
Is anybody have a solution ?
When you just change $el.dblclick to $el.click it will also handled with $(document).click(submitChanges); event. So $el.click handler should return false to stop further event processing.
$el.click(function (e) { // <---------- click
tempVal = $el.html();
$edittextbox.val(tempVal).insertBefore(this).bind('keypress', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
submitChanges();
}
}).select();
$el.hide();
$(document).click(submitChanges);
return false; // <------------------------ stop further event handling
});
http://jsfiddle.net/zvm8a7cr/
You may use the contenteditable attribute of html
var initialContent = $('.text-content').html();
$('.text-content')
.on('blur', function(){
if(initialContent != $(this).html())
alert($(this).text());
if($(this).html() == ''){
$(this).html(initialContent);
}
})
.on('click', function(){
if(initialContent == $(this).html()) {
$(this).html('');
}
});;
.text-content {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wrapper">
<span contenteditable="true" class="text-content">Click On Me!</span>
</div>
Related
Hi I have multiple divs on the page. I want to raise an alert based on a user hovering over one of the divs and pressing control z. I need to in effect alert out what is in the span dependant upon which div the user is hovered over on.
I have tried with getbyId the problem arises with multiple elements. I am unsure if i need to bind every element.
<div class="mydiv">Keypress here!<span>test</span></div>
<div class="mydiv">Keypress here!<span>test1</span></div>
var pressed = false;
onload = function(e) {
var myElement = document.getElementsByTagName('div');
function keyaction(e, element) {
// var originator = e.target || e.srcElement;
if (e.charCode === 122 && e.ctrlKey) {
//myElement.innerHTML += String.fromCharCode(e.charCode);
alert(true);
}
}
for (var i = 0; i < myElement.length; i++) {
myElement[i].addEventListener("mouseover", function (e)
{
document.addEventListener("keypress", function(t){keyaction(t,e);}, false);
});
myElement[i].addEventListener("mouseout", function ()
{
document.removeEventListener("keypress", keyaction, false);
});
}
}
I think you are overdoing for what is needed. A simple keydown event bind on mouseover and unbind on mouseout would do the trick.
Here's an example :
<div id="wrapper">
<div class="mydiv">Keypress here!<span>test</span></div>
<div class="mydiv">Keypress here!<span>test1</span></div>
</div>
<br>
Keys Pressed :
<br>
<div id="key"></div>
$("#wrapper .mydiv").on("mouseover",function()
{
$(document).bind("keydown",function(e) {
var originator = e.keyCode || e.which;
if(e.ctrlKey)
$("#key").append(originator + ",");
});
}).on("mouseout",function()
{
$(document).unbind("keydown");
});
http://jsfiddle.net/s095evxh/2/
P.S : for some reason , Jsfiddle doesn't allow keydown event on mouseover so you might have to click manually on the div to make it work but the solution works flawless on a local system.
I would suggest that you use the normalized e.which if available. You also have code 122 which is F11 keys code not 90 related to the 'z' key.
Turn the event manager on when over and off when not per your stated desire:
$('.mydiv').on('mouseenter', function () {
$(window).on('keydown', function (e) {
var code = e.which ||e.keyCode;
$('#status').append('we:'+ code);
if (code === 90 && e.ctrlKey) {
$('#status').append('howdy');
}
});
});
$('.mydiv').on('mouseleave', function () {
$(window).off('keydown');
});
Note that I changed to post some text to a fictitious "status" div rather than your alert as that will change where the cursor hovers. Change that to some real action. There MAY be issues with the event bubbling but I will leave that determination to you.
Here is a key code list (google for more/another) https://gist.github.com/lbj96347/2567917
EDIT: simple update to push the span text into the status div:
<div class="mydiv">Keypress here!<span>test</span>
</div>
<div class="mydiv">Keypress here!<span>test1</span>
</div>
<div id="status">empty
<div>
$('.mydiv').on('mouseenter', function () {
var me = this;
$(window).on('keydown', function (e) {
var code = e.which || e.keyCode;
$('#status').append('we:' + code);
if (code === 90 && e.ctrlKey) {
$('#status').append($(me).find('span').text());
}
});
});
$('.mydiv').on('mouseleave', function () {
$(window).off('keydown');
$('#status').text('out');
});
Listen for the keypress on the window and add mouse events to the elements to toggle a variable with what element is active.
var activeElem = null;
$(".mydiv")
.on("mouseenter", function () {
activeElem = $(this);
}).on("mouseleave", function () {
if(activeElem && activeElem.is(this)) {
activeElem = null;
}
});
$(window).on("keydown", function (evt) {
if( activeElem && evt.keyCode===90 && evt.ctrlKey) {
console.log(activeElem.find("span").text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">Keypress here!<span>test</span></div>
<div class="mydiv">Keypress here!<span>test1</span></div>
To prevent frequent binding/unbinding of the "keydown" handler whenever the user hovers over the <div>, I would simply keep track of the <div> currently being hovered. Something like this:
var hovering = null;
$(document)
.on('keydown', function(e) {
if (e.which === 90 && e.ctrlKey && hovering) {
console.log($('span', hovering).text());
}
})
.on('mouseover', '.mydiv', function(e) {
hovering = this;
})
.on('mouseout', '.mydiv', function() {
hovering = null;
});
.mydiv:hover {
cursor: pointer;
color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">Test <span>1</span></div>
<div class="mydiv">Test <span>2</span></div>
<div class="mydiv">Test <span>3</span></div>
<div class="mydiv">Test <span>4</span></div>
<div class="mydiv">Test <span>5</span></div>
I would propose the other way around. Listen for the keypress, and select the element which has the hover.
$(document).keypress(function(e) {
if (e.charCode === 26 && e.ctrlKey) {
console.log("Key pressed");
console.log($('.mydiv:hover span').html());
}
});
Codepen Demo
If I am understanding your question correctly, you are looking for the text value of the span within the hovered element. Traversing the DOM from $(this) will get you what you want.
$(".mydiv").mouseover(function (e) {
alert($(this).find('span').text());
});
I've got a working inline edit script which lets the user edit his or her name.
But it currently does not "save" when the user hits the enter key
The script:
<span class="pageTitle" id="username">Visitor 123123981203980912 <span class="iconb" data-icon=""></span></span>
// Inline edit
$.fn.inlineEdit = function(replaceWith, connectWith) {
$(this).hover(function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
});
$(this).click(function() {
var elem = $(this);
elem.hide();
elem.after(replaceWith);
replaceWith.focus();
replaceWith.blur(function() {
if ($(this).val() != "") {
connectWith.val($(this).val()).change();
elem.html($(this).val() + ' <span class="iconb" data-icon=""></span>');
}
$(this).remove();
elem.show();
});
});
};
var replaceWith = $('<input name="temp" type="text" class="inlineEdit" />'),
connectWith = $('input[name="hiddenField"]');
$('#username').inlineEdit(replaceWith, connectWith);
How can i make the above also react when the enter key is hit?
You need to detect the enter press and do the same thing in blur function. Add the following to your js. Demo
replaceWith.keypress(function(e) {
if(e.which == 13) {
if ($(this).val() != "") {
connectWith.val($(this).val()).change();
elem.html($(this).val() + ' <span class="iconb" data-icon=""></span>');
}
$(this).remove();
elem.show();
}
});
This should fire when the enter key is pressed inside the input:
$('#username').live("keypress", function(e) {
if (e.keyCode == 13) {
// action here
}
});
You can call the same function on keydown and check for e.keyCode for enter key which is 13..a fiddle would be helpful..
Also check this link
Thanks,
Hardik
I have two buttons in a form and want to check which one was clicked.
Everything works fine with radioButtons:
if($("input[#name='class']:checked").val() == 'A')
On simple submit button everything crash.
Thanks!
$('#submit1, #submit2').click(function () {
if (this.id == 'submit1') {
alert('Submit 1 clicked');
}
else if (this.id == 'submit2') {
alert('Submit 2 clicked');
}
});
You can use this:
$("#id").click(function()
{
$(this).data('clicked', true);
});
Now check it via an if statement:
if($("#id").data('clicked'))
{
// code here
}
For more information you can visit the jQuery website on the .data() function.
jQuery(':button').click(function () {
if (this.id == 'button1') {
alert('Button 1 was clicked');
}
else if (this.id == 'button2') {
alert('Button 2 was clicked');
}
});
EDIT:- This will work for all buttons.
$('input[type="button"]').click(function (e) {
if (e.target) {
alert(e.target.id + ' clicked');
}
});
you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.
$('#btn1, #btn2').click(function() {
let clickedButton = $(this).attr('id');
console.log(clickedButton);
});
try something like :
var focusout = false;
$("#Button1").click(function () {
if (focusout == true) {
focusout = false;
return;
}
else {
GetInfo();
}
});
$("#Text1").focusout(function () {
focusout = true;
GetInfo();
});
This is my HTML structure.
<div id="dvHirearachy" class="MarginTB10">
<span>
<label>Hierarchy Names</label><br />
<input type="text" name="txtHierarchy" />
<a id="ancRemove" href="#">Remove</a>
</span><br />
<a id="ancNew" href="#">New Hierarchy Name</a>
</div>
On click of anchor tag "ancNew" , I am generating again the complete span tag above mentioned in the markup.
The problem is on click of textbox also the span structure is getting generated. Same problem i was facing on click of "ancRemove" for that i tried to stop the event bubbling, it has worked for this but not for the textbox.
my script.
$(document).ready(function () {
$("#ancRemove").click(function (e) {
RemoveHierarchy(this, e);
});
$("#ancNew").click(function (e) {
generateNewHierarchy(e);
});
});
function generateNewHierarchy(e) {
if (window.event) {
var e = window.event;
e.cancelBubble = true;
} else {
e.preventDefault();
e.stopPropagation();
var container = createElements('span', null);
$(container).append(createElements('input', 'text'));
$(container).append(createElements('a', null));
$(container).append("<br/>").prependTo("#ancNew");
$(container).children('input[type=text]').focus();
}
}
function createElements(elem,type) {
var newElem = document.createElement(elem);
if (type != null) {
newElem.type = "input";
newElem.name = "txtHierarchy";
$(newElem).addClass('width_medium');
}
if (elem == "a") {
newElem.innerHTML = "Remove";
$(newElem).click(function (e) {
RemoveHierarchy(this,e);
});
}
return newElem;
}
function RemoveHierarchy(crntElem, e) {
e.stopPropagation();
$(crntElem).parents("span:first").remove();
}
what is the way to avoid the situation.
Check this jsfiddle :
http://jsfiddle.net/xemhK/
Issue is prepandTo statement, It is prepading the elements in #ancNew anchor tag, thats why all textbox and remove anchor, are propagating click event of #ancNew, and it is calling generateNewHierarchy() function.
Change in $(container).append("<br/>").prepandTo("#ancNew"); to $(container).append("<br/>").insertBefore("#ancNew");
function generateNewHierarchy(e) {
if (window.event) {
var e = window.event;
e.cancelBubble = true;
} else {
e.preventDefault();
e.stopPropagation();
var container = createElements('span', null);
$(container).append(createElements('input', 'text'));
$(container).append(createElements('a', null));
//$(container).append("<br/>").prepandTo("#ancNew");
$(container).append("<br/>").insertBefore("#ancNew");
$(container).children('input[type=text]').focus();
}
}
and in createElements
if (elem == "a") {
newElem.innerHTML = "Remove";
$(newElem).attr("href","#").click(function (e) {
RemoveHierarchy(this,e);
});
}
The following script enables the submit button if a form if is filled up.
However I have a textarea
<textarea id="description" tabindex="15" style="width:500px;" name="description" cols="80" rows="10">
and I can not know how to add it for checking. If I type in all textboxes and leave the textarea empty, it will be submitted.
$(document).ready(function () {
$('form').delegate('input:text, input:checkbox', 'blur keyup click change', function () {
if(($('form input:text').filter(function(){ return $.trim(this.value) == ''; }).length > 0))
{
$('#btnUpdate').attr("disabled", true);
}
else {
$('#btnUpdate').removeAttr("disabled");
}
});
});
Thank you
Try changing this:
$('form').delegate('input:text, input:checkbox', // rest of line
to
$('form').delegate('input:text, input:checkbox, textarea',
EDIT
The code should be:
$(document).ready(function () {
$('form').delegate('input:text, input:checkbox, textarea', 'blur keyup click change', function () {
if(($('form input:text, form textarea').filter(function(){ return $.trim(this.value) == ''; }).length > 0)) {
$('#btnUpdate').attr("disabled", true);
} else {
$('#btnUpdate').removeAttr("disabled");
}
});
});
$(document).ready(function () {
$('form').delegate('input:text, input:checkbox', 'textarea', 'blur keyup click change', function () {
if(($('form input:text').filter(function(){ return $.trim(this.value) == ''; }).length > 0&&$('textarea').val()!==""&&$('textarea').val()!==null))
{
$('#btnUpdate').attr("disabled", true);
}
else {
$('#btnUpdate').removeAttr("disabled");
}
});
});