How to bold label on click? - javascript

So the labels are populated from the database. Once the label is clicked, the label need to turn red and bold. when clicked on another label, the first label need to come back to original state and the new label should be activated and it needs to be bold and red. for some reason, the changeActiveStates() only works for the first 2 labels, i.e., when first label is clicked it turns red and when the second label is clicked the first label is turned black and the second label is turned red. when the third label is clicked, the second label remains red and the third one turns red. How do i fix this??
Here is the code:
<html>
<span>
<input type="hidden" name="LiabFilter" id= "idLib<%=liabkey %>" value="<%=liabkey %>" />
<div>
<label for="idLib<%=liabkey%>" id="liablabel" style="cursor: hand; padding-left: 25px; font-weight: normal"
onClick ="clearLiabFilter();
document.getElementById('idLib<%=liabkey%>').checked = true;
changeActiveStates(this);">
<%=liab.getName() %>
</br>
</label>
</div>
</span>
<style type="text/css">
.activate { font-weight: bold; color:#e40000;}
.visited{ font-weight: normal; color: #000000;}
</style>
<script>
function byId(id) {
return document.getElementById ? document.getElementById(id) : document.all[id];
}
var prevLink = "";
function changeActiveStates(ele) {
if (prevLink) byId(prevLink).className = '';
ele.className = 'activate';
prevLink = ele.id;
}
</script>
</html>

Are you averse to JQuery?
If not, this should work.
$('label').click(function() {
$('label').removeClass('activate'); /* Remove 'activate' class from all labels */
$(this).addClass('activate'); /* Add 'activate' class to clicked label
});
EDIT: Example on jsFiddle
EDIT: A little more detail as the questioner hasn't used JQuery before.
JQuery is a javscript library and so must be loaded by the browser before you can do all the nifty stuff.
Add the following between the <head></head> tags on your page:
<script src="http//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
(Why let google host JQuery for you?)
Then add the following, also between the tags but after the script tag given above:
$(document).ready(function() {
$('label').click(function() {
$('label').removeClass('activate'); /* Remove 'activate' class from all labels */
$(this).addClass('activate'); /* Add 'activate' class to clicked label
});
});
(What does $(document).ready() do?)

Maybe not the best of solutions, but have you considered using jQuery? It's generally not too much of a dependency , and will solve these sort of issues quite elegantly and easily for you. Plus. Cross-browser compatibility.

Related

How to delete HTML section using a function of js?

I need to remove a HTML section using a button. The button is in the HTML section I want to remove. And the section I want to remove was previously added by a button.
With Add section button I add a section below the first section, but I can't create a function to remove a section, I can't select the section I want to remove.
image of web
You're able to use the remove() method in order to do that.
Example:
HTML:
<div id="testID">your stuff.</div>
<button onclick="deleteDiv()">Delete</button>
JS:
function deleteDiv() {
var selectedDiv = document.getElementById("testID");
selectedDiv.remove();
}
try this code:-
<p id ="remove" style = "color: green; font-size: 24px; font-weight: bold;">
on click remove this section
</p>
<button onClick = "remove()">
click here
</button>
var htmlElement = document.getElementById('remove'); //use getElemeyId or getElementsByClassName According to your need;
function remove() {
htmlElement.remove();
}

JavaScript: How to change color to only part of the string in an input field?

I have an input field where I would like to have the characters turn red after the 10th symbol.
So far I have:
var street_1 = document.getElementById('street_1');
street_1.style.color = "red";
Which changes the color of all the characters. Then I tried using:
street_1.value.substring(10,100).style.color = "red";
which of course didn't work since .style as I learned only works for the entire field and not just the value.
Since im completely new to JS I really have no idea how to approach this.
You can hide the input field, and add another span element that displays its value as follows:
HTML:
<div>
<input type="text">
<span class="text"></span>
</div>
CSS:
input {
opacity: 0;
width: 100%;
}
div {
position: relative;
border: 1px solid #000;
}
.text {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
.red {
color: red;
}
JS:
var span = document.querySelector('span');
var input = document.querySelector('input');
input.addEventListener('keydown', function(evt) {
var value = evt.target.value;
span.innerHTML = value.substring(0, 10) + '<span class="red">' + value.substring(10) + '</span>'
});
You can find a working fiddle here https://jsfiddle.net/v127c14p/
in html you can't define sub elements in the value of input fields because it is allways a simple string and not a html element. so you only can define the color for the input element and the complete text.
<input type="text" value="my <em style='color: red;'>test</em>"> is not possible
<input type="text" value="my test" style="color: red;"> is the only way to mark the text
what can be a sollution, define a simple div tag, write the value of your input filed inside that, and mark the text in that div tag by surrounding with a span tag and setting a class to this
Edit:
best practice is, simply show a red border on the input field and tell the user with a popup what exactly is wrong with his input (bootstrap modals or jquery-confirm.js for excample)
Note: If I explicitly need an <input> field and not just user-editable text, this solution won't work!
It is a quite old question, but maybe someone finds this solution helpful.
It uses the contenteditable tag, to allow the user to type / change text in an normal HTML element and JS to check and color the text.
The field check can, for example, also be done with "onkeyup" for immediate feedback to the user, but this will also reset the text cursor to the beginning of the field.
HTML:
<a id="sample_id" onblur="color_overlength_func('sample_id', 20)" contenteditable="true">Some Text</a>
JS:
function color_overlength_func(textfield_id, max_length) {
let text_temp = document.getElementById(textfield_id).innerHTML;
if (text_temp.length >= max_length) {
let text_OK = text_temp.substr(0, max_length);
let text_to_long = text_temp.substr(max_length);
document.getElementById(textfield_id).innerHTML = "" + text_OK + "<em style='color:red;'>" + text_to_long + "</em>";
}
}
You can find a working fiddle here: https://jsfiddle.net/kyh9803c/
You can do a substring and append a element like span and then target the span with css or js directly.
You can use CSS. Although javascript library need to load everytime
you mean something like this
<div>
HELL<span class="red" style="color:red">O</span>
</div>

change label css class for checkbox if checked

I have checkboxes that are hidden. I have images as the labels for the checkboxes, so that when the images are clicked the checkboxes are clicked. I am trying to make it so that the image has different opacities depending on whether the box is checked or not. Here is my css for the image label:
.checkbox-label{
opacity: .2;
}
.checkbox-label:hover{
opacity: .5;
}
.checkbox-label-after-click{
opacity: 1;
}
Here is my javascript to move the classes
<script>
$('.checkbox-label').click(function(){
var the_input = $(this).next('input');
if(the_input.checked){
$(this).addClass( "checkbox-label-after-click" );
} else {
$(this).removeClass("checkbox-label-after-click");
}
});
</script>
Basically, when someone clicks on the label, it should grab the next input, which is the checkbox, the label's classes should change. I've also tried switching the addClass and removeClass methods, which makes the class switch work on the first click, but never after.
Here is the html:
How do I get this to work?
I would do this with pure CSS, like this:
label {
cursor: pointer;
}
/* Change cursor when the label is hovered */
input[type=checkbox] {
display: none;
}
/* Hide the ugly default radio styling */
label > span {
opacity: 0.2;
}
/* Hide the checkmark by default */
input[type=checkbox]:checked + span {
opacity: 1;
color: green;
}
/* Show the checkmark when the radio is checked */
<label>
<input type="checkbox" name="obvious"><span>✓</span> I look good.</label>
<br/>
<label>
<input type="checkbox" name="obvious"><span>✓</span> Cause we've been re-styled!</label>
<br/>
<label>
<input type="checkbox" name="obvious"><span>✓</span> I've got a green checkmark if you click me.</label>
<br/>
<label>
<input type="checkbox" name="obvious"><span>✓</span> We are a family of checkmarks!</label>
You can simply use toggleClass(). Your code is not working as the_input is a jQuery object and it doesn't have checked property. You can use .get() to get underlying DOM element.
like
the_input.get(0).checked or the_input[0].checked
As per your code
$('.checkbox-label').click(function(){
$(this).toggleClass( "checkbox-label-after-click", the_input.get(0).checked ); //You can also use the_input.prop('checked')
});
Im guessing its falling down when checking its checked. You will be better off just toggling the class when you click the label
$('.checkbox-label').click(function(){
$(this).toggleClass( "checkbox-label-after-click" );
});
If you really want to check its state, you could do something like this:
$('.checkbox-label').click(function(){
var the_input = $(this).next('input');
if(the_input.prop('checked')){
$(this).addClass( "checkbox-label-after-click" );
} else {
$(this).removeClass("checkbox-label-after-click");
}
});
Use the_input.prop('checked') to see if the input is checked or not. It returns a boolean.
As the_input is a jquery object you cannot use checked property of javascript, you may use the_input[0].checked or use prop method.
Replace this:
if(the_input.checked){
With this:
if(the_input.prop('checked')){

Hover over one span and change background color of that span plus another one by adding and removing a class

<span id="english">Yes</span>
<span id="spanish">Sí</span>
How can I hover over any of these and change background color to yellow on both. I can't use onmouseout() because the background color changes dynamically due to other scripts.
I'm aware that I can add a class skipping the use of jQuery -although it's a valid choice if all else fails- by using something like:
document.getElementById(id).className += " yellow";
and the css would be:
.yellow {
background-color: yellow
}
My previous solution that included onmouseout() was:
function chbg(color, id1, id2) {
document.getElementById(id1).style.backgroundColor = color;
document.getElementById(id2).style.backgroundColor = color;
}
and the HTML:
<span id="english" onmouseover="chbg('yellow', 'english', 'spanish')" onmouseout="chbg('white','english', 'spanish')">Yes</span>
<span id="spanish" onmouseover="chbg('yellow', 'english', 'spanish')" onmouseout="chbg('white','english', 'spanish')">Sí</span>
Use JQuery hover function instead.
Try this:
$(document).ready(function(){
$("span").hover(
function(){
$('span').css('background', 'yellow');
},
function(){
$('span').css('background', 'white');
});
});
JSFiddle Demo #1 (With Class)
JSFiddle Demo #2 (Without Class)
UPDATE #1
Use toggleClass() function instead.
$(document).ready(function(){
$("span").hover(function(){
$('span').toggleClass('highlight');
});
});
JSFiddle Demo
UPDATE #2
Assign a class to all the span that needs to be highlighted. For example: class="highlight". Using toggleClass() to toggle a class from CSS will add another class now. This way only span with .highlight change color.
JSFiddle Demo
This can be done with only CSS, by adjusting your HTML a bit:
<span id="bghover">
<span>Yes</span>
<span>Sí</span>
</span>
And for the CSS:
#bghover span
{
background-color: white;
}
#bghover:hover span
{
background-color: yellow;
}
So you wrap the two spans into a span or div with id bghover, which is only used as a trigger for CSS :hover. If there's no hover, all spans within #bghover are white, if there is a hover (similar to onmouseover), all spans within #bghover are white.

JQuery toggle Q&A: individual Q&As don't operate correctly unless you click on Open All/Close All first

I have a Q&A list with "Open All/Close All" at the top with individual open and close image buttons that toggle when clicked. That works fine.
Then follow individual Q&As, and each has its own open and close image.
If you click on "Open All/Close All" first, as soon as the page loads, and then click on the individual Q&A open/close images, all works fine. But if after page load you click on the individual Q&A open/close images, bypassing "Open All/Close All," they display the inappropriate open or close image.
Here is page code:
<div class="answersee"><span>Open All</span><img src="assets/open.gif" border="0" alt="" /></div>
<div class="answerhide"><span>Close All</span><img src="assets/close.gif" border="0" alt="" /></div>
<div class="qa">
<div><img src="open.gif" border="0" alt="" /><span class="question">Question.</span></div>
<div class="answer"><p>Answer.</p></div>
</div>
Here's the script (also uses Jquery):
$(function () {
$(".qa").click(function () {
$(this).find("div").next().slideToggle("fast");
if ($(this).find("div:eq(0)").find("img").attr("src") == "open.gif") {
$(this).find("div:eq(0)").find("img").attr("src", "close.gif");
}
else {
$(this).find("div:eq(0)").find("img").attr("src", "open.gif");
}
});
$(".answersee").click(function () {
$(".answer").show("fast");
$(".qa > div > img").attr("src", "close.gif");
$(".answerhide").show();
$(".answersee").hide();
})
$(".answerhide").click(function () {
$(".answer").hide("fast");
$(".qa > div > img").attr("src", "open.gif");
$(".answersee").show();
$(".answerhide").hide();
})
});
I don't think it's a CSS problem, or I'd include that code here. Do I need to initialize the script in some way? Or did I make a mistake in the above script?
Here's how I would do it.
Working Demo →
EDIT:
Update the code to have simple open/close link.
Code with comments which explains my approach:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style>
body
{
font-family: "Verdana";
font-size: 12px;
}
.question
{
background-color: #ccc;
cursor: pointer;
padding: 5px;
margin-bottom: 10px;
border-bottom: 1px solid #000;
}
.answer {
padding: 5px;
}
</style>
<script>
$(document).ready(
function()
{
//Hide all the answers on page load.
$('.answer').hide();
//For all questions, add 'open'/'close' text.
//You can replace it with an image if you like.
//This way, you don't need to specify img tag in your HTML for each question.
$('.question')
.append(' <span>[ open ]</span>');
//Now there are two ways to toggle the visibility of answer.
//Either click on the question OR click on Open All / Close All link.
//To use the same code for both instances, we will create
//a function which will take the 'question' div and toggle the answer for it.
//Advantage of this approach is that the code to toggle the answer is in
//one place.
//By default, this function will try to toggle the status of the answer
//i.e. if it's visible, hide it otherwise show it.
//This function will take a second argument called 'showAnswer'.
//If this argument is passed, it overrides the toggle behavior.
//If 'showAnswer' is true, answer is shown.
//If it's false, answer is hidden.
//This second parameter will be used by the 'openAll', 'closeAll' links.
var toggleAnswer = function toggleAnswer(question, showAnswer)
{
//The way I have structured the HTML, answer DIV is right after
//question DIV.
var $answer = $(question).next('div');
//Animation callback, after the animation is done, we want to
//switch the 'text' to display what could the user do with the question.
//Once again, you can change this code to show open/close image.
var updateText = function()
{
var text = $answer.is(':visible') ? ' [close] ' : ' [open] ';
$(question).find('span').html(text);
}
var method = null;
if(arguments.length > 1)
{
//If the function was called with two arguments, use the second
//argument to decide whether to show or hide.
method = showAnswer === true ? 'show' : 'hide';
}
else
{
//Second argument was not passed, simply toggle the answer.
method = $answer.is(':visible') ? 'hide' : 'show';
}
$answer[method]('fast', updateText);
};
//On each question click, toggle the answer.
//If you have noticed, I didn't enclose both Q&A inside one DIV.
//The way you have done if user clicks on the answer, answer will collapse.
//This may not be desirable as user may want to copy the answer
//and he won't be able to.
$('.question').click(function(){ toggleAnswer(this);});
//We will reuse the same toggleAnswer method in openAll, closeAll
//handling. This way, if you want to change behavior of how the question/answers
//are toggled, you can do it in one place.
$('#openClose').click(
function()
{
var showAnswer = $(this).html().toLowerCase().indexOf('open') != -1 ? true : false;
$('.question').each(function() { toggleAnswer(this, showAnswer); });
$(this).html(showAnswer ? 'Close All' : 'Open All');
return false;
}
);
}
);
</script>
<html>
<head>
<title>simple document</title>
</head>
<body>
<a id='openClose' href='#'>Open All</a>
<br /><br />
<div class='question'>Question 1</div>
<div class='answer'>Answer 1</div>
<div class='question'>Question 2</div>
<div class='answer'>Answer 2</div>
<div class='question'>Question 3</div>
<div class='answer'>Answer 3</div>
</body>
</html>
You need to use the callbacks because your animation will not have finished by the time to check for which image is being shown.
$(".qa").click(function() {
$(this).find("div").next().slideToggle("fast", toggleImage);
}
function toggleImage(){
var $img = $(this).find("img");
$img.attr('src') == "open.gif" ? $img.attr('src', "close.gif") : $img.attr('src', "open.gif");
}
N.B There are better ways to do this but lets get you working first and then see if you want to refactor it some more.
Thank you for taking the time to provide this. I will try this later today and report back. In my version, I toggle the Open All/Close All feature. It's a cleaner look and easier to use, since you don't have to move your mouse.
Redsquare and Solution Yogi:
Thanks. I will reply again later and also post a working demo so you can see the problem more clearly. Sorry, I should have done that before.
Liz

Categories

Resources