Change label color on active inputbox - javascript

Do someone know why this not work?
I want to change the color of the label from a input box when the box is active.
The JavaScript:
$("input").focus(function() {
var inputID = document.activeElement.id;
document.getAnonymousElementByAttribute('label','for', inputID).setAttribute('class', 'active');
});
The HTML:
<label for="username">Username</label>
<input name="username" id="username" type="text"><br>
<label for="passwort">Passwort</label>
<input name="passwort" id="passwort" type="password"><br>
<input type="submit" class="button" value="login">
The CSS:
.active{
color: #FFA500 !important;
}
I hope someone can help me :)

With your current HTML:
$('input').focus(function(){
$(this).prev().addClass('active');
}).blur(function(){
$(this).prev().removeClass('active');
});
JS Fiddle demo.
Or, with on() (assuming you're using jQuery 1.7, or above):
$('input').on('focus blur', function(e){
var prev = $(this).prev();
prev[e.type == 'focus' ? 'addClass' : 'removeClass']('active');
});
JS Fiddle demo.
More abstracted (so the HTML stucture doesn't matter), selecting by the for attribute:
$('input').on('focus blur', function(e){
var label = $('label[for="' + this.id + '"]');
label[e.type == 'focus' ? 'addClass' : 'removeClass']('active');
});
JS Fiddle demo.
References:
addClass().
Attribute-equals ([attribute="value"]) selector.
blur().
focus().
on().
prev().
removeClass().

$('input').on('click', function(){
$(label).toggleClass('active');
});
Your overcomplicating things, keep it simple, sometimes a developers most useful tool is the backspace key.

Try input:focus instead of .active in your CSS code. Omit !important as well.
input:focus{
color: #FFA500;
}

You mix jQuery functions with non-jQuery. Try to use only jQuery functions to handle your task. In my example below I changed .focus() to .on('focus',callback) which is same but just more understandable. In jQuery you should get target of your event and wrap it by $(). You also can use this but I try not to use it by several reasons. Then you can apply any of many jQuery methods:
$("input").on('focus', function(ev) {
var t = $(ev.target);
t.addClass('active');
});

See here for a very basic example: http://jsfiddle.net/zn5fB/
And here, for an event-triggered example: http://jsfiddle.net/zn5fB/1/
Setting a style with JavaScript usually follows the following format:
document.getElementById("abc").style.[css property name in camel case] = "[value]";
You will find that it is very common to use a library such as jQuery to make this (and many other things) a little easier. With jQuery, you can write code like:
// find all elements with the tag name "bar" that are direct
// descendants of an element with the class name "foo"
$(".foo > BAR").css("color", "red");

Related

How to add same function for two classs?

There is a jQuery code that already works how I want. .foto class do the function. But I should to add .fotoleft class to do the same function. How can I do the same function for two different classes?
$(document).ready(function() {
$(".foto").click(function() {
$src = $(this).attr("src");
if (!$("#light-box").length > 0) {
$("body").append("<div id='light-box'> <span class='close'></span><img src=''></div>");
$("#light-box").slideDown();
$("#light-box img").attr("src", $src);
} else {
$("#light-box").slideDown();
$("#light-box img").attr("src", $src);
}
});
$("body").on("click", "#light-box", function() {
$("#light-box").slideUp();
});
});
You just need to use Multiple Selector (“selector1, selector2, selectorN”)
$(".foto, .fotoleft ") .click(function(){
//Your existsing code
});
If you want .fotoleft to perform the same function as .foto, I find the most efficient way of doing this would be to use .foto in your html twice, rather than in your JS twice.
I prefer this method as it makes it easier to apply a function to multiple or additional elements without needing to add more classes to the JS.
i.e.
<a class='foto'>Do Something</a>
<a class='foto fotoleft'>Do Something too></a>
You could choose to amend your css to make .foto more compatible in this way so you don't overwrite any styling.
You use groups (via a comma); these are CSS selectors, after all:
$(".foto, .fotoleft")...
You may use
$(".foto, .fotoleft") .click(function(){

jquery button value to title

I have a lot buttons all over a site with a value (the text of the button) and each has, for example a bootstrap class of '.btn-default':
<input type="button" value="Clear" class="form-control input-sm btn-default" onclick="doingSomethingElseEtc();">
How might I use jQuery to get the value of the button and bind it to a title attribute to each button, so if you moused over the button, you'd get the default browser tooltip containing the string from the button value, etc..?
For example, just to get the gist of what I'm asking:
$('.btn-default').attr('title', $(".btn-default").val());
I'm trying to touch the code as little as possible, etc..
Thank you!
You can use each to iterate each button and set the titles.
$('.btn-default').each(function(i,obj){
$(obj).attr('title', $(obj).val());
});
No need for any arguments, or variables, or other whatzit. :-)
$('.btn-default').each(function () {
$(this).attr('title', $(this).val());
});
Demo
Your idea will work too, if you're adding a function to the attr like this:
$('.btn-default').attr('title', function() {
//console.log($(this).val(), $(this).text());
return $(this).val() || $(this).text();
});
This will add to each button with class btn-default the title attribute.
I think it's also good to get the text because your button could be defined with input value=".." or with <button>text</button>
Please have a look at the demo below and in this jsFiddle.
$('.btn-default').attr('title', function() {
//console.log($(this).val(), $(this).text());
return $(this).val() || $(this).text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="Clear" class="form-control input-sm btn-default" onclick="doingSomethingElseEtc();">
<button class="btn-default">test1</button>
<button class="btn-default">test2</button>
When you read the value of a collection of elements, jQuery only returns the value of the first one in the set. So you need to iterate over all of them and set the title on each one.
$('.btn-default').each( function () {
var elem = $(this);
elem.attr('title', elem.val());
});
Downside to this is if there is a lot of elements, it will be slow. Also you need to do this on document ready.

Get a variable immediately after typing

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.

How to set text decoration for "this".sibling

I'd like to make a text decoration of `line-through' when a checkbox is checked and remove the decoration when the checkbox is unchecked.
This is my js:
if ($(this).is(':checked')) {
$(this).siblings('label').style.textDecoration = "line-through";
} else {
$(this).siblings('label').style.textDecoration = "none";
}
With the current code I get the error of
Uncaught TypeError: Cannot set property 'textDecoration' of undefined
and I'm assuming it is because it doesn't like my this.siblings string.
try this one.
$(this).siblings('label').css('text-decoration', 'line-through');
$(this).siblings('label').css('text-decoration', 'none');
If your label is after the checkbox input, you can use plain CSS and the Next Sibling operator +
input[type=checkbox]:checked + label{
text-decoration: line-through;
}
<input type="checkbox" id="a1" name="a1"><label for="a1">UNCHECKED</label>
if it's not an immediate sibling than you can use the Sibling Operator ~ instead of +.
.style is plain JS and refers to only one element while you're handling an array of jQuery selectors Elements.
So yes, user jQuery's .css() method to apply the changes to all your elements (jQuery will loop all of them internally like you would in JS using for loop or forEach)
If you want you can also do it using a conditional operator ?: (without the if else) simply like:
$(':checkbox').on("change", function(){
$(this).siblings('label').css({"text-decoration": this.checked ? "line-through" : "none"});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type="checkbox" id="a1" name="a1"> <label for="a1">UNCHECKED</label>
</p>
If you want you can mix jQuery and JS here's an example:
$("#element")[0]/*or use .get(0)*/.style.textDecoration = "none";
but as I've said before it cannot be applied to multiple elements if not used inside a loop, passing that current index as the get value:
$(".elements").each(function(i){
$(this)[i].style.textDecoration = this.checked ? "line-through" : "none" ;
});
which is a mix of jQuery and JS's:
for(var i=0; i<myJSelements.length; i++){
myJSelements[i]/* etc... */
}
Does .sibling('label') return an element or Text?
If it returns Text, then that is your problem.
Apply .style.textDecoration to the element.
The function identifies the text node in the element and decorates it.

how to create an editable input on click event

So I have a page that I want to use to allow users to see what in currently in the database and edit them by clicking on the box.
I have a pretty hacky method that works for text imputs but for a drop down box or date selector completely falls apart.
my HTML
<td name='joineddate133'>
<input type='date'
id='joind133'
name='joinda133
value='2012-03-15'
class='toedit'
readonly='readonly'
onclick='enablejoindate(this.id)'
size='20' />
< /td>
The current Javascript
<script>
function enablejoindate(joindatid){
$(function(){
$("input:text[id="+ joindatid +"]").removeAttr("class");
$("input:text[id="+ joindatid +"]").removeAttr("readonly");
$("input:text[id="+ joindatid +"]").addClass("inlineditjoind");
});
}
</script>
The inlinedit class is used as a marker so the jquery can find it easily to post and the toedit class currently just hides the attributes.
Obviously this solution isn't great and I would like to try and work out a better way to maybe create an input on the double click function etc.
You could have all fields as readonly and hidden until focussed:
$("table").on("focus", "input, select", function(){
$(this)
.prop("readonly", false)
.removeClass("toedit");
});
$("table").on("blur", "input, select", function(){
$(this)
.prop("readonly", true)
.addClass("toedit")
.siblings("span").text($(this).val());
});
$("table").on("click", "td", function(){
$(this).children().focus();
});
DEMO (updated again)
You should take a look at X-editable.
<a
href="#"
id="joinda133"
data-type="date"
data-viewformat="dd.mm.yyyy"
data-pk="1"
data-placement="right"
data-original-title="Date you've joined"
>25.02.2013</a>
Since you are using jQuery, use a jQuery event. It's best to set readonly to false with the prop() method:
$('input[type=date]').on('click', function(){
$(this)
.removeClass("toedit")
.prop("readonly", false)
.addClass("inlineditjoind");
});
JSFiddle
Have a look to the DEMO JSFiddle
JS/JQUERY -
$("#joind133").on('click',function(){
$(this).removeProp("readonly")
.removeClass("toedit")
.addClass("inlineditjoind");
});
HTML -
<td name='joineddate133'>
<input type='date' id='joind133' name='joinda133' value='2012-03-15' class='toedit' readonly='readonly' size='20'/>
</td>
UPDATE ON REQUEST FOR MAKING IT GENERIC BINDING
$("input[type='date']").on('click',function(){
$(this).removeProp("readonly")
.removeClass("toedit")
.addClass("inlineditjoind");
});

Categories

Resources