js clicking adds color - javascript

I have a question. So basically i'm trying to create a js script, when user clicks on a link, it colors the link in different color and then adds the link to an input box, and when the user clicks again on the same link, it changes the color back to original and deletes the text from the input box. The purpose whould be as a search filter, where you can add to search box, predefined keywoards.
$('.tagsSelect a').click(function() {
var clickColor = this.style.color;
if(clickColor = "#F5EBD5"){
var value = $(this).text();
var input = $('#popGirlMenu');
input.val(input.val() + value + ', ');
this.style.color="#f5d47f";
return false;
}
if(clickColor = "#f5d47f") {
var value = $(this).text();
var input = $('#popGirlMenu');
input.val(input.val() - value - ', ');
this.style.color="#F5EBD5";
return false;
}
});
This is my code, it works, bet when the user clicks again on the link, it doesn't change the color back to original and it doesn't remove the text from input box.
p.s sorry for my bad english

Use CSS for your layout, and check the class instead of a color value:
CSS
a { color: blue; }
a.selected { color: red; }
HTML
link a
link b
<input id="txt" type="text" />
JavaScript
$("a").click(function() {
var $this = $(this);
$this.toggleClass("selected");
if ($this.hasClass("selected"))
$("#txt").val($("#txt").val() + $this.text() + ", ");
else
$("#txt").val($("#txt").val().replace($this.text() + ", ", ""));
});
See this jsFiddle
Note to remove a part from a string, you need to replace that part with an empty string. - doesn't work on strings.

Use == or === (comparison) instead of = (setting a variable)

Related

I am trying to replace the selected word in Quill Library with an ID from an Input that I create dynamically ANGULAR

Change the selected word "TEST" with the ID of the Input "1"
With this code I am able to get the selected word and actually replace it with a hard coded dummy text but that only happens when I click inside the editor..
replaceSelection(event) {
var range = this.quill.getSelection();
if (range) {
if (range.length == 0) {
console.log('User cursor is at index', range.index);
} else {
var text = this.quill.getText(range.index, range.length);
console.log('User has highlighted: ', text);
this.quill.deleteText(range.index, range.length);
var clickedElement = event.target;
console.log(`clickedElement`, clickedElement)
// Get the id of the clicked element
var id = event.target.id;
console.log(`id:`);
this.quill.insertText(range.index, '{{' + id + '}}');
}
} else {
console.log('User cursor is not in editor');
}
}
}
When I click the Input ID this line is called:
console.log('User cursor is not in editor');
As said in API docs .getSelection will return null if editor has no focus. When you click on button that is not inside editor, you lose focus from editor.
However you can provide first argument, that will focus editor before getting selection range.
You just need to change your code to:
var range = this.quill.getSelection(true);
Editor will retain previous selection.

To get alert message, if color dialog was closed without change in color selection (warning: colorDialog.style.display = "none";)

This is the code on js fiddle for tests https://jsfiddle.net/em7yfa12/
And also code is here:
But as first let me explain what code does. And then I will tell what I need to achieve. I can not find the way by myself. That's why I am asking here for the solution.
When "Open input element to insert text " button is pressed prompt element appears to get text, which will be later painted to the color which was selected in color dialog.
But this event will happen only when color will be changed, because the event is triggered from change in color dialog.
This is all regular. But I need something extra and that is:
If color dialog was opened and no change in color was performed before dialog was closed, then I need to get:
alert("You have to select a different color than any of colors you have selected in previous cases to paint the text");
<input type="button" id="newlabelID" value="Open input element to insert text "/></br>
<input type="color" id="colorDialogID" ></br>
<a id="aID"> Text to paint</br>
var someText;
function createStatusF(){
someText = prompt("Enter some text :", "");
if ((someText=="")||(someText==null)){
return;
}
document.getElementById("colorDialogID").focus();
document.getElementById("colorDialogID").value = "#FFCC00";
document.getElementById("colorDialogID").click();
}
document.getElementById("newlabelID").onclick = createStatusF;
document.getElementById("colorDialogID").style.display = "none";
function peintTheText(){
document.getElementById("aID").innerHTML= someText;
var theColor=document.getElementById("colorDialogID").value;
document.getElementById("aID").style.color=theColor;
}
document.getElementById("colorDialogID").onchange = peintTheText;
You need to use the input event and attach it to the color input. This works, but it's not a good idea to use alert with the color picker, since the color picker will have a higher z index than the alert, hence the user will not be able to click it.
Here's the JS code:
let someText;
let previousColors = [];
let colorDialog = document.getElementById("colorDialogID");
function openColorPicker() {
colorDialog.focus();
colorDialog.value = "#FFCC00";
colorDialog.click();
}
function createStatusF() {
someText = prompt("Enter some text :", "");
if ((someText == "") || (someText == null)) {
return;
}
openColorPicker();
}
document.getElementById("newlabelID").onclick = createStatusF;
document.getElementById("colorDialogID").style.display = "none";
function peintTheText() {
var theColor = colorDialog.value;
previousColors.push(theColor);
document.getElementById("aID").innerHTML = someText;
document.getElementById("aID").style.color = theColor;
}
function onColorSelected(e) {
const theColor = colorDialog.value;
if (previousColors.includes(theColor)) {
alert("You have to select a different color than any of colors you have selected in previous cases to paint the text");
}
}
colorDialog.addEventListener('input', onColorSelected);
colorDialog.addEventListener('change', peintTheText);
Working Fiddle

Is it possible to add a suffix to a jQuery mask?

I'm using Igor Escobar's jQuery mask plugin (https://github.com/igorescobar/jQuery-Mask-Plugin) and I'm trying to add a suffix to a mask to show a % sign at the end of the input value.
The application I'm building is for Brazilian users, then I have to use this number format: 000.000,00. Where , (comma) is the decimal separator and . (dot) is the thousand separator.
I wrote the following code to apply the mask, not yet appending the % sign at the end of it.
$('.mask-decimal').each(function () {
var $self = $(this);
var precision = parseInt($self.data('precision'), 10) || 2;
var mask = '#.##0,' + (new Array(precision + 1).join('0'));
$self.mask(mask, {
reverse : true,
maxlength : false
});
$self.on('keyup', function () {
var val = this.value;
if (val) {
if (val.length <= precision) {
while (val.length < precision) {
val = '0' + val;
}
val = '0,' + val;
} else {
var parts = val.split(',');
parts[0] = parts[0].replace(/^0+/, '');
if (parts[0].length === 0) {
parts[0] = '0';
}
val = parts.join(',');
}
this.value = val;
}
});
});
This mask works perfectly.
What I tried to do was add the percent symbol at the end of the mask, then remove it just in the beginning of my keyup handler, and finally append it again before return the value. I basically changed these lines:
var mask = '#.##0,' + (new Array(precision + 1).join('0')) + '%';
var val = this.value.replace('%', '');
this.value = val + '%';
After change that, I can input a value in the field, but I can't clear/change it using backspace. If I'm fast enough I can select the entire content and delete it, but it's an awful solution for regular users. It happens this way because the cursor stays always at the end of the input and the keyup event is triggered very quickly.
With that in mind, there is a way to move the cursor to a specific position inside the input? Does somebody can see another way to change my function so the user can use the backspace to clear the input contents?
If this is for an input field and the % sign is just for decoration, you could position a span containing the symbol above the input. Because it's purely a display item, right? Or you could have the sign after the input.
There's absolutely no need to have it in the input if the user's not supposed to be able to edit it. It's counterintuitive both for the user and for your logic.
Here I put the sign inside a label just so that clicking it will activate the input field.
label, input {
font-size:18px;
font-family:sans-serif;
}
label {
margin-left:-24px;
}
input {
text-align:right;
padding-right:24px;
}
<input type="text" id="number" value="123">
<label for="number">%</label>

Clone jquery mobile input field with data-clear-btn="true"

Using jquery and jquery mobile I try to make a dynamic form. Input fields are created or removed so that always one empty input field is left.
This is my jquery code to achieve this (try it here:
http://jsfiddle.net/SR864/17/):
$(document).ready(function() {
var total = 1;
// add new field
$("#bar").on("input", ".input", function() {
// add new field
if ($(".input").last().val() != "") {
var newFields = $(this).closest("p").clone();
newFields.find(":input").each(function() {
var name = $(this).attr('name').replace('-' + (total - 1), '-' + total);
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('');
total++;
});
$(this).closest("p").after(newFields);
}
});
$("#bar").on("input", ".input", function() {
// remove empty field
if ($(this).val() == "") {
$(this).closest("p").remove();
}
});
});
I also would like to have "delete-buttons" inside of the input fields to remove the text from the input fields. jquery mobile provides data-clear-btn="true" for that. However, somehow the behavior of data-clear-btn="true" only works for the first input field - the new (cloned) ones don't get the clear button.
Question
How can I have the clear-buttons for the cloned input fields?
Bonus question
What is necessary to have input fields deleted when they are empty after the clear button is pressed?
jQM wraps input fields in a div ui-input-text. You need to clone input itself - not the wrapping div - change its' id, name, val()...etc. Then add it to form and enhance it using .textinput() function.
Moreover, you should wrap code in pagecreate event.
$(document).on("pagecreate", function () {
var counter = 0;
$("#bar").on("input", function (e) {
if ($(e.target).val().length === 1) { /* after 2 characters add a new input */
counter++;
var id = "input-" + counter;
var input = $(e.target).clone().prop({
id: id,
name: id
}).val("");
$(e.target).closest(".ui-input-text").after(input);
$("#" + id).textinput();
}
});
});
Demo
I had a check at the problem. By default the cross button (which is an tag) has a class 'ui-input-clear-hidden' which keeps it hidden till you type. Though you are cloning the element after you start typing, the duplicate element also has this class which keeps it hidden (may be cloning is done before the class 'ui-input-clear-hidden' is removed). So I suggest removing the class 'ui-input-clear-hidden' from your cloned object explicitely as shown below.
$("#bar").on("input", ".input", function() {
// add new field
if ($(".input").last().val() != "") {
var newFields = $(this).closest("p").clone();
newFields.find(":input").each(function() {
var name = $(this).attr('name').replace('-' + (total - 1), '-' + total);
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('');
total++;
});
$(this).closest("p").after(newFields);
}
/* New line Added for Fix*/
newFields.find('a').removeClass('ui-input-clear-hidden');
});

When user enters correct text, an image rollovers/changes

I am designing a language learning site. I want to have it when someone enters text into the text box it starts to roll over certain images. Take a look at my sample below
http://imageshack.us/photo/my-images/827/hiraganaquiz2.jpg/
So, when the user enters "na" the first symbol highlights as you see in my sample. When he enters "ma" the second symbol should highlight/rollover. I want all the symbols to stay rolled over while the correct text is entered. so if the user types "nama" the first two symbols should be rolled over to show they got it correct and once the last correct text is entered all three will be rolled over.
Can this by done? I will accept advanced and simple methods.
$(document).ready(function() {
var text = ['na', 'ma', 'ba'];
$("#elemID").on('keyup', function() {
var typed = this.value;
$.each(text, function(index, item) {
if (typed.indexOf(item)!=-1) {
$('li', 'ul').eq(index).find('img').addClass('correct');
}else{
$('li', 'ul').eq(index).find('img').removeClass('correct');
}
});
});
});
FIDDLE
EDIT:
At the top of your page, in the <head> section, add:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Then wrap the code in document.ready, see the edited code above on how to do that ?
On change of the input box, you could do something like this: (totally untested)
var parts = ["na", "ma", "blah"];
var start = 0;
for (var i = 0; i < parts.length; i++) {
var currentPart = parts[i];
var $img = $(".images img:nth-child(" + i + ")");
var end = start + currentPart.length;
if (str.length >= end && str.slice(start, start + currentPart.length) == currentPart) {
$img.addClass("highlight");
} else {
$img.removeClass("highlight");
}
start += currentPart.length;
}

Categories