How to get value if div is focused in jquery? - javascript

Here I am having one div and one input text. I can get the input element value which is focused, but couldn't get the div value.
If I use .val(), I can get the input text value.
If I use .html(), I can get div element value.
But, I need the value of whatever is focused.
HTML
<div class="tab_common tab_addclass" tabindex="-1">4</div>
<input class="text-input tab_addclass" id="other-input"/>
<button type="button" id="btn">Validate</button>
JS
$(document).on ('click', '.tab_addclass', function(){
$('.tab_addclass').each(function() {
if($(this).hasClass('tab_focus'))
{
suc_flg=1;
$(this).removeClass('tab_focus');
}
});
$(this).addClass('tab_focus');
});
$(document).on ('click', '#btn', function(){
alert($('.tab_focus').val());
});
CSS
.tab_focus {
border: 2px solid #7ECC27;
background-color: #F2F2F2;
}
.tab_common{
border: 2px solid #d4d4d4;
border-radius: 4px;
cursor: pointer;
}
div {
background: #fff;
margin: 20px;
}
div:focus {
border: 2px solid #7ECC27;
}
JSFIDDLE

$(document).on ('click', '.tab_addclass', function(){
$('.tab_addclass').each(function() {
if($(this).hasClass('tab_focus'))
{
suc_flg=1;
$(this).removeClass('tab_focus');
}
});
$(this).addClass('tab_focus');
});
$(document).on ('click', '#btn', function(){
var test = $('.tab_focus').html()||$('.tab_focus').val()
alert(test);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="tab_common tab_addclass" tabindex="-1">4</div>
<input class="text-input tab_addclass" id="other-input"/>
<button type="button" id="btn">Validate</button>

Updated answer that returns the value of the most recently focused div or input following a button click:
$(document).on('click', '#btn', function () {
var focusExist = $(".focus").length;
if (focusExist) {
$focus = $(".focus");
if ($focus.hasClass("tab_common")) {
var tabValue = $focus.text();
alert(tabValue);
} else {
var inputValue = $focus.val();
alert(inputValue);
}
}
});
$(document).on('focus', '.tab_addclass', function () {
$(".focus").removeClass("focus");
$(this).addClass("focus");
});
Updated Fiddle

You have to loop through your elements and check if it is div then get the text otherwise take the input value:
$(document).on ('click', '#btn', function(){
var val = {};
$('.tab_addclass').each(function(){
if($(this).is('div')){
val.div = this.textContent;
}else{
val.input = this.value;
}
});
$('p').text(JSON.stringify(val));
});
p{background:black; color:white;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tab_common tab_addclass" tabindex="-1">4</div>
<input class="text-input tab_addclass" id="other-input" value='input value' />
<button type="button" id="btn">Validate</button>
<br><br><br><br>
<p></p>

Use jQuery's keydown() funtion.
$(function(){
$('.tab_focus').keydown(function(){
alert($(this).val());
});
});

Try this in your js
alert($('.tab_focus').val() | $('.tab_focus').html());

Related

Is there a more efficent way to do this?

How can I achieve this code easier or with less lines of code?
I'm curious if it can be done easier and/or more efficently. Because I feel like there is too much repetition in this, so there must be an easy way.
And I'm not only planning to make 4 of this but like 20-30, so performance is a key aspect.
Jquery:
$( document ).ready(function() {
$( "#q1" ).click(function() {
$( "#a1" ).slideToggle( "slow", function() {});
if ($(this).hasClass('on')){
$(this).removeClass('on');
}else{
$(this).addClass('on');
}
});
$( "#q2" ).click(function() {
$( "#a2" ).slideToggle( "slow", function() {});
if ($(this).hasClass('on')){
$(this).removeClass('on');
}else{
$(this).addClass('on');
}
});
$( "#q3" ).click(function() {
$( "#a3" ).slideToggle( "slow", function() {});
if ($(this).hasClass('on')){
$(this).removeClass('on');
}else{
$(this).addClass('on');
}
});
$( "#q4" ).click(function() {
$( "#a4" ).slideToggle( "slow", function() {});
if ($(this).hasClass('on')){
$(this).removeClass('on');
}else{
$(this).addClass('on');
}
});
});
HTML:
<div id="faq_content">
<div class="faq_box">
<div class="questions" id="q1">
<span>xyz</span>
</div>
<div class="answers" id="a1">
<span>xyz</span>
</div>
</div>
<div class="faq_box">
<div class="questions" id="q2">
<span>xyz</span>
</div>
<div class="answers" id="a2">
<span>xyz</span>
</div>
</div>
</div>
The easiest way that I can think of, given your HTML structure, is the following:
$(document).ready(function() {
// selecting all the elements you need to work with,
// and binding the anonymous function of the click()
// method as the event-handler:
$("#q1, #q2").click(function() {
// here $(this) will refer to the element that fired the
// click event, from that element:
$(this)
// we navigate to the next-sibling element matching the
// supplied selector:
.next('.answers')
// we use the slideToggle() method to show/hide the element,
// using an Arrow function to compose the anonymous
// function so that we can use the same this (and therefore
// $(this)) as the outer function:
.slideToggle('slow', () => {
// here $(this) still refers to the clicked element, as
// Arrow functions don't establish their own 'this'; and
// we use the toggleClass() method to add, or remove, the
// supplied class based on whether it already exists on
// the element:
$(this).toggleClass('on');
});
// here we again call the click() method, without arguments, in
// order to fire the click event on page-load (which, in this
// context will cause the answers to be hidden on page-load):
}).click();
});
$(document).ready(function() {
$("#q1, #q2").click(function() {
$(this).next('.answers').slideToggle('slow', () => {
$(this).toggleClass('on');
});
}).click();
});
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.faq_box {
border: 1px solid #000;
margin: 0.2em auto;
width: 80vw;
}
.questions {
background-color: #ffff;
border: 1px solid transparent;
border-bottom-color: #000;
cursor: pointer;
font-size: 1.2em;
font-weight: bold;
transition: background-color 0.3s linear;
}
.questions::before {
content: attr(id) ': ';
text-transform: capitalize;
}
.answers::before {
content: attr(id) ': ';
}
.on {
background-color: #0f06;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="faq_content">
<div class="faq_box">
<div class="questions" id="q1">
<span>xyz</span>
</div>
<div class="answers" id="a1">
<span>xyz</span>
</div>
</div>
<div class="faq_box">
<div class="questions" id="q2">
<span>xyz</span>
</div>
<div class="answers" id="a2">
<span>xyz</span>
</div>
</div>
</div>
References:
click().
next().
slideToggle().
$(document).ready(function(){
var qClasses = $('.q');
qClasses.on('click', function(){
var $this = $(this);
var aIds = $this.data('id');
$(aIds).slideToggle("slow");
$this.toggleClass("on");
});
});
Since all the #q1,#q2... are doing the same thing on click you can utilize the classes for this and with <div id="#q1" class="q" data-id="#a1" ></div> you can refer to the id on click of the q classes. Also, you can define the initial state of #q1 or q classes as there are only two states with class "on" or without it so the default state can be defined directly in HTML instead of checking in the JS. like: <div id="#q1" class="q on" data-id="#a1"></div>
Because all your handlers look the same, you can create a function which returns a function:
function createHandler(selector) {
return function() {
$( selector ).slideToggle( "slow", function() {});
if ($(this).hasClass('on')){
$(this).removeClass('on');
}else{
$(this).addClass('on');
}
}
}
and use it like this:
$( "#q1" ).click(createHandler("#a1"))
To find out more about this principle search for "Higher-Order Functions" and "Closures"

Parent listener $(this) listening to all selected child elements

When user clicks on add an item a new item append on the parent element, then clicking on that item a textarea prompts to edit its text.
HTML DOM / JS Fiddle
<div class="editor"></div>
add an item
<div class="options">
<br><b>Item Text</b> <br>
<textarea class="itemtext"></textarea>
</div>
JS(jQuery) / JS Fiddle
var $item = "<div class='item'>Text here...</div>",
$itembtn = $('a.additem'),
$editor = $('div.editor'),
$opt = $('div.options');
$itembtn.on('click', function(e){
e.preventDefault();
$editor.show();
$editor.append($item);
});
$($editor).on('click', 'div.item', function(){
var $this = $(this);
$opt.show();
$opt.find('textarea').val($this.text());
$opt.find('textarea').on('keyup', function(){
$this.text($opt.find('textarea').val());
});
});
$($editor).on('blur', 'div.item', function(){
$opt.hide();
});
But it seems that $(this) is not pointing to a single clicked element, instead it is pointing to all the clicked/selected child elements!
And also the blur event is not working!
How i can point $this to only one selected item but not all the clicked items?
Well, this was easy...
Change this:
$($editor).on('click', 'div.item', function(){
var $this = $(this);
console.log($this);
$opt.show();
$opt.find('textarea').val($this.text());
$opt.find('textarea').on('keyup', function(){
$this.text($opt.find('textarea').val());
});
});
Into this:
$($editor).on('click', 'div.item', function(){
var $this = $(this);
console.log($this);
$opt.show();
$opt.find('textarea').unbind('keyup').keyup(function(){
$this.text($opt.find('textarea').val());
}).val($this.text());
});
Since you are adding .on([...]) per element, you are adding always a new event listener. You can .unbind() it so it won't be tied to that element. And then you re-bind it.
In this context, using .on() is BAD
One way is to keep a variable of your current 'active' div (clicked div), and use that to set the text.
Fiddle
var $item = "<div class='item'>Text here...</div>",
$itembtn = $('a.additem'),
$editor = $('div.editor'),
$opt = $('div.options'),
$txt = $opt.find('textarea'),
$curtxt;
$itembtn.on('click', function(e){
e.preventDefault();
$editor.show();
$($item).appendTo($editor).click(function(){
$curtxt = $(this);
$txt.val($curtxt.text());
$opt.show();
$txt.select().focus();
});
});
$txt.keyup(function(){
$curtxt.html($txt.val().replace(/\r?\n/g, '<br>'));
}).blur(function(){
$opt.hide();
});
Before adding the keyup event destroy the keyup event you added on click of the div and yes its done
Use $(element).off('keyup') to unbind the previous keyup event and then add the current event using $(element).on('keyup',function).
Check the snippet
var $item = "<div class='item'>Text here...</div>",
$itembtn = $('a.additem'),
$editor = $('div.editor'),
$opt = $('div.options');
$itembtn.on('click', function(e){
e.preventDefault();
$editor.show();
$editor.append($item);
});
$($editor).on('click', 'div.item', function(){
var $this = $(this);
$opt.show();
var txtEd = $opt.find('textarea');
txtEd.val($this.text());
txtEd.off('keyup').on('keyup', function(){
$this.text($opt.find('textarea').val());
});
});
$($editor).on('blur', 'div.item', function(){
$opt.hide();
});
.editor { margin: 20px 0px; border: 1px solid #888; padding: 5px; display: none; }
.item { background: #ccc; margin: 5px; padding: 5px; }
.options textarea { width: 80%; height: 100px; }
.options { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="editor"></div>
add an item
<div class="options">
<br><b>Item Text</b> <br>
<textarea class="itemtext"></textarea>
</div>

Js remove all classes from element

I have a button and when I click on it I want to remove all the classes. That's what I've tried so far:
button.style.className = ''
document.querySelector('button').onclick = function() {
this.style.className = '';
}
.myClass {
color:red;
}
.second {
color:green;
}
<button class="myClass second">click me</button>
Now I can't use classList.remove because I doen't know the class names, they are dynamic.
How can I remove all the classes from an element?
Do not access className from the style object, access it directly like
this.className
document.querySelector('button').onclick = function() {
this.className = '';
}
.myClass {
color:red;
}
.second {
color:green;
}
<button id="button" class="myClass second">click me</button>
HTML DOM removeAttribute() Method:
document.querySelector('button').onclick = function() {
this.removeAttribute("class");
}
.myClass {
background-color:red;
}
.second {
box-shadow: 0px 0px 10px 10px;
}
<button id="button" class="myClass second">click me</button>
Use this.classname instead of this.style.className. Your Javascript code will be like this:
document.querySelector('button').onclick = function() {
this.className = ''; //remove the .style
}
Fiddle.
You can remove (.style) and after that everything works fine.
button.className = '';
or you can use this.className = "";
both works fine.

Click on edit jquery

I am a newbie so my question is pretty simple and straight forward.
I have a simple html text. When I click on that html text, the text should change to input field with the value retained and when the user clicks outside the text box, the input text field now should change to html text.
<div class="myText"> Hellow World </div>
Can somebody do this in jquery/Meteor. I am actually building a meteor project
You can do that with the contenteditable attribute
<div class="myText" contenteditable="true"> Hellow World </div>
<!-- Your div is now editable -->
Updated DEMO jsFiddle
$(document).ready(function() {
$('.editable').on('click', function() {
var that = $(this);
if (that.find('input').length > 0) {
return;
}
var currentText = that.text();
var $input = $('<input>').val(currentText)
.css({
'position': 'absolute',
top: '0px',
left: '0px',
width: that.width(),
height: that.height(),
opacity: 0.9,
padding: '10px'
});
$(this).append($input);
// Handle outside click
$(document).click(function(event) {
if(!$(event.target).closest('.editable').length) {
if ($input.val()) {
that.text($input.val());
}
that.find('input').remove();
}
});
});
});
In my solution you need to add class="editable" to all editable divs.
You also need to set position: relative to these divs. May be you can update my code and edit the css:
.editable {
position: relative;
}
To correctly align the input inside the div, you need to remove the border or set the .css({}) of the input to left: -1px and top: -1px. The border actually pushes the input 1px left and 1px form the top.
Try this:
$(function() {
$('div.myText').on('click', function() {
var div = $(this);
var tb = div.find('input:text');//get textbox, if exist
if (tb.length) {//text box already exist
div.text(tb.val());//remove text box & put its current value as text to the div
} else {
tb = $('<input>').prop({
'type': 'text',
'value': div.text()//set text box value from div current text
});
div.empty().append(tb);//add new text box
tb.focus();//put text box on focus
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="myText">Hello world</div>
<div class="myText">This is second</div>
Try this:
$(document).click(function() {
$('.myText').html("Hello World");
});
$(".myText").click(function(event) {
$('.myText').html("<input type='text' id='test' value='Hello World'/>");
$('#test').focus();
event.stopPropagation();
});
FIDDLE.
To do it very easily and understandable you can also make two elements instead of changing.
Working fiddle: http://jsfiddle.net/45utpzhx/
It does an onClick event and onBlur.
html
<div>
<span class="myText">Hello World</span>
<input class="myInput" />
</div>
jQuery
$(document).ready(function() {
$(".myText").click(function() {
$(this).hide();
var t = $('.myText').html();
$('.myInput').val(t);
$('.myInput').show();
});
$(".myInput").blur(function() {
$(this).hide();
var t = $('.myInput').val();
$('.myText').html(t);
$('.myText').show();
});
});
Replace the clicked element with an input with value equal to the clicked element's text
$(document).on('click', '.myText', function() {
var that = $(this);
var text = that.text();
that.wrap('<div id="wrp" />');
$('#wrp').html('<input type="text" value="' + text + '" />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="myText"> Hellow World </div>
You can try this solution :
$('.myText').click(function(){
var m = $(this).text();
$(this).html('');
$('<input/>',{
value : m
}).appendTo(this).focus();
});
$(document).on('blur','input',function(){
var m = $(this).val();
$(this).parent().find('input').remove().end().html(m);
});
working DEMO
$('#text').on('click', function() {
$("#text").hide();
if ($("#text").text()=="Add New text"){
$('#in_text').val("");
}else{
$('#in_text').val($("#text").text());
}
$("#in_text").show();
});
// Handle outside click
$(document).click(function(event) {
if(!$(event.target).closest('.editable').length) {
if($("#text").css('display') == 'none'){
$("#in_text").hide();
if ($("#in_text").val()=="" ){
$('#text').text("Add New text");
$('#text').addClass("asd");
}else{
$('#text').removeClass("asd");
$('#text').text($("#in_text").val());
}
$("#text").show();
}
}
});
#in_text{
display:none;
}
.editable{
width:50%;
}
.asd{
border-bottom : 1px dashed #333;
}
#text{
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="editable">
<div id="text" >Text in div</div>
<input type="text" placeholder="Add New Text" id="in_text"/></div>

create an array with values of selected images

Im trying to gather the images selected, take their values, put them into an array, and then push them to a mysql database.
Here is my current code
$(document).ready(function() {
var startfind = $("body").find('.on').val();
var awnsers = $('.on').map(function() {
return $(startfind).text();
}).get().join(',');
$("img").click(function() {
$(this).toggleClass("on");
});
$('button').click(function() {
alert(awnsers);
});
});
#seasoning {
margin: 8px;
font-size: 16px;
height: 100px;
width: 100px;
}
.on {
padding: 10px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://i.imgur.com/7HyU4yh.jpg" id="seasoning" value="0">
<br>
<img src="https://i.imgur.com/OEHCjCK.jpg" id="seasoning" value="1">
<br>
<button>Submit</button>
I can't get the alert to show the values of the items selected.
You can trigger an event when you click on an image
Then listen on that event, an update the answer
use answer when you need it
an I change a little in your html code, that change img's value attr to data-value
============Here is the code and jsFiddle=======================
$(function(){
//catch this values, because you will use these for more than one time
var answers = [];
function getAnswers(){
answers = []; //empty old answers so you can update it
$.map($('.on'), function(item){
answers.push($(item).data('value'));
});
}
//init the answers in case you use it before click
getAnswers();
$(document).on('click', 'img', function(e){
e.preventDefault();
$(this).toggleClass('on');
//trigger the state change when you click on an image
$(document).trigger('state-change');
});
//get answers when event was triggered
$(document).on('state-change', function(e){
getAnswers();
});
$('#btn-show').click(function(){
alert(answers.join(',') || 'nothing was selected');
});
});
#seasoning {
margin: 8px;
font-size: 16px;
height: 100px;
width: 100px;
}
.on {
padding: 10px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://i.imgur.com/7HyU4yh.jpg" id="seasoning" data-value="0">
<br>
<img src="https://i.imgur.com/OEHCjCK.jpg" id="seasoning" data-value="1">
<br>
<button id="btn-show">Submit</button>
Please check this code.
$("img").on('click',function() {
$(this).toggleClass("on");
});
$(document).on('click', 'button', function() {
var awnsers = $('.on').map(function() {
return $(this).attr('value');
}).get().join(',');
alert(awnsers);
});
Working fiddle - http://jsfiddle.net/Ashish_developer/6ezf363a/

Categories

Resources