Delete specific text from form when clicked - javascript

Basically I want to make a function that, when the text is clicked, it prints the 'id' on the form. and when it's clicked again, only that 'id' is deleted (prior clicked/printed 'id's remain).
The print script I have so far:
function imprime01(obj) {
document.form2.text.value = document.form2.text.value + obj.title;
}
the div
<div onclick="imprime01(this);" title="240 ">240</div>
<div onclick="imprime01(this);" title="230 ">230</div>
<div onclick="imprime01(this);" title="220 ">220</div>
So what I want is: when I click 240, 230 it prints "240 230" on the form, and when I click "240" again, it deletes only "240" from the form. Is there a way to achieve this?

There are many ways to do this.
I would store your ids in an array. In your click handler, test for the existence of the id in your array and remove it if it exists, otherwise add it. Then write all the ids in the array to your text box:
var idList = [];
function imprime01(obj) {
var id = obj.title;
var idIndex = idList.indexOf(id);
if (idIndex > -1) {
idList.splice(idIndex, 1);
}
else {
idList.push(id);
}
document.form2.text.value = idList.join(" ");
}
This may be a little more involved than a simple string replacement, but it gives you other functionality that could be useful later. For example, if another part of your program needs to know which ids have been selected, they are already available in an array.
Edit: Rather than storing the array in a variable, you could generate it on the fly in your click handler with string.split(" "):
function imprime01(obj) {
var id = obj.title;
var idList = document.form2.text.value.split(" ");
var idIndex = idList.indexOf(id);
if (idIndex > -1) {
idList.splice(idIndex, 1);
}
else {
idList.push(id);
}
document.form2.text.value = idList.join(" ");
}​
Working demo: http://jsfiddle.net/gilly3/qWRct/

See http://jsfiddle.net/BdEMx/
function imprime01(obj) {
var arr=document.form2.text.value?document.form2.text.value.split(' '):[];
var i=arr.indexOf(obj.title);
if(i===-1){
arr.push(obj.title);
}else{
arr.splice(i,1);
}
document.form2.text.value = arr.join(' ');
}
You shouldn't add a space at the end of title attributes only because you want to join some of them.

Use replace and indexOf functions:
var str = document.form2.text.value;
if(str.indexOf(obj.title) != -1)
document.form2.text.value = str.replace(obj.title,"");
else
document.form2.text.value = str + obj.title;

Related

Get JavaScript Object

I am working client side on a web page that I am unable to edit.
I want to use JS to click on a particular button, but it does not have a unique identifier.
I do know the class and I do know a (unique) string in the innerHTML that I can match with, so I am iterating through the (varying number) of buttons with a while loop looking for the string:
var theResult = '';
var buttonNum = 0;
var searchString = '720p';
while (theResult.indexOf(searchString) == -1
{
theResult = eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum + \"].innerHTML\");
buttonNum++;
}
Now I should know the correct position in the array of buttons (buttonNum-1, I think), but how do I reference this? I have tried:
eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum-1 + \"].click()")
and variation on the position of ()'s in the eval, but I can't get it to work.
You could try something like:
var searchStr = '720p',
// Grab all buttons that have the class 'streambutton'.
buttons = Array.prototype.slice.call(document.querySelectorAll('button.streamButton')),
// Filter all the buttons and select the first one that has the sreachStr in its innerHTML.
buttonToClick = buttons.filter(function( button ) {
return button.innerHTML.indexOf(searchStr) !== -1;
})[0];
You don't need the eval, but you can check all the buttons one by one and just click the button immediately when you find it so you don't have to find it again.
It is not as elegant as what #Shilly suggested, but probably more easily understood if you are new to javascript.
var searchString = '720p';
var buttons = document.getElementsByClassName("streamButton"); // find all streamButtons
if(buttons)
{
// Search all streamButtons until you find the right one
for(var i = 0; i < buttons.length; i++)
{
var button = buttons[i];
var buttonInnerHtml = button.innerHTML;
if (buttonInnerHtml.indexOf(searchString) != -1) {
button.click();
break;
}
}
}
function allOtherClick() {
console.log("Wrong button clicked");
}
function correctButtonClick() {
console.log("Right button clicked");
}
<button class='streamButton' onclick='allOtherClick()'>10</button>
<button class='streamButton' onclick='allOtherClick()'>30</button>
<button class='streamButton' onclick='correctButtonClick()'>720p</button>
<button class='streamButton' onclick='allOtherClick()'>abcd</button>
I would stay clear of eval here, what if the text on the button is some malicious javaScript?
Can you use jQuery? if so, check out contains. You can use it like so:
$(".streamButton:contains('720p')")

Overwrite text with javascript

I want to overwrite some standard text from my CMS.
<form accept-charset="UTF-8" action="/da-DK/listings" class="new_listing"
enctype="multipart/form-data" id="new_listing" method="post"
novalidate="novalidate"><div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓"><input name="authenticity_token" type="hidden"
value="vvEeH5tHhuGME4jNDPhw0o4w8KoWpwgchgrU7xG/7LQ="></div>
<label class="input" for="listing_title">CHANGE THIS TEXT</label>
I want to change the text where it says "CHANGE THIS TEXT" using javascript. I know very basic javascript though, so I hoped someone here could help me.
I already have code that enables me to change a text with an ID, but this label doesn't have an ID, so I don't know how to go about it.
Thank you for your time.
The script can only be posted in the head section of the whole site (even though it's specific to one ingle page).
Here is my other script that worked for ID:
<script>
var texts = [];
texts["new-listing-link"] = "NEW TEXT HERE";
var interval = setInterval(function() { setText(); }, 100);
function setText() {
var textsCopy = texts.slice();
for (var key in texts) {
var element = document.getElementById(key);
if (element != null) {
element.innerHTML = texts[key];
delete texts[key];
}
}
if (texts.length == 0) {
window.clearInterval(interval);
}
}
</script>
How can I go about it? :)
I'm pretty sure I'm only allowed to use javascript and not jQuery
Here's another way, no need to change what you've got
document.querySelector('label[for=listing_title]').innerHTML = 'New Label';
no jQuery bloat, no fumbling through arrays, quick and simple
querySelector works just like jQuery, but it has native speed and zero bloatage.
label[for=listing_title] finds the label that has an attribute "for" with the value "listing_title" ... so, while not guaranteed to be unique, not many forms have more than one label "for" an input
var texts = {}; // note {} not []
texts["label[for=listing_title]"] = "NEW TEXT";
var interval = setInterval(function() {
setText();
}, 100);
function setText() {
var textsCopy = texts.slice(); // why???
for (var key in texts) {
var element = document.querySelector(key);
if (element != null) {
element.innerHTML = texts[key];
delete texts[key];
}
}
if (texts.length == 0) {
window.clearInterval(interval);
}
}
With the above version, you can mix id's as well as the more complex selectors ... so, your original substitution could be done as well in the same loop by adding
texts["#new-listing-link"] = "NEW TEXT HERE";
Note the '#' before the id
Another hint or two:
var texts = {
"label[for=listing_title]": "NEW TEXT",
"#new-listing-link": "NEW TEXT HERE"
}; // declare the text object in one go
var interval = setInterval(setText, 100); // this is equivalent (not exactly identical, but functionally identical to your code
// rest of your code
The script can only be posted in the head section of the whole site (even though it's specific to one ingle page).
Here is my other script that worked for ID:
<script>
var texts = [];
texts["new-listing-link"] = "NEW TEXT HERE";
var interval = setInterval(function() { setText(); }, 100);
function setText() {
var textsCopy = texts.slice();
for (var key in texts) {
var element = document.getElementById(key);
if (element != null) {
element.innerHTML = texts[key];
delete texts[key];
}
}
if (texts.length == 0) {
window.clearInterval(interval);
}
}
</script>
How can I go about it? :)
I'm pretty sure I'm only allowed to use javascript and not jQuery
This should do the trick (quick'n'dirty):
slice=Function.prototype.call.bind([].slice);
slice(document.querySelectorAll(".input")).map(function(x){ return x.textContent="Killroy was here"; });
Check the Fiddle
MDN on Array.prototype.slice()
MDN on Array.prototype.map()
MDN on Document.querySelectorAll()
If you need just this label, choose:label[for=listing_title] as in Jaromanda Xs answer
var label = document.getElementsByTagName("label")[0] // If this is the first label of the page
label.value = "new text";

javascript not changing the text color

I have a function that I want to change the font color of the user entered string if it is equal to a certain word located in an array.. So far when I step through it it says that it changes the font color but it actually never updates it to the screen and I don't know why. Here is what I have so far
function getLastWord() {
var input = document.getElementById("my_text");
//var input = document.getElementById(textArea.value);
//var lineIn = document.getElementById(my_text).innerHTML;
var inputValue = input.value;
var lastWordTyped
var changeColorOfWord;
if (input == null) {
input == " ";
}
//lastWordTyped = input.substr(input.trim().lastIndexOf(" ") + 1);
lastWordTyped = inputValue.substr(inputValue.trim().lastIndexOf(" ") + 1);
if (input != null) {
for (var i = 0; i < reservedKeyWords.length; i++) {
if (reservedKeyWords[i] === lastWordTyped) {
lastWordTyped = lastWordTyped.fontcolor("blue");
my_text.replace(inputValue, lastWordTyped);
} else {
}
}
}
}
I see two issues with the code thus far.
You are using 'fontcolor("blue")' parameter on the lastWordTyped. The proper syntax to change color is element.style.color="#CCC".
You will need to wrap the last typed word in a span so you can target it and apply the color to just that word.
string.fontcolor is legacy, and should not be used even though I could see it as a viable option in this case
Essentially, what you are doing is adding font tags around the word:
var txt = 'hello world';
txt = txt.fontcolor('blue');
//txt = '<font color="blue">hello world</font>';
You do not show what you do with the result, but if you actually put it in an HTML element it should work, even though instead of using fontcolor, I'd rather use element.style.color. This would require slightly more work though:
var ele = document.querySelector('#my_text');
ele.style.color = 'blue';
ele.innerHTML = lastWordTyped;
If you still want to go with the .fontcolor method, you could just keep what you have in the question and add
input.innerHTML = my_text;

Auto highlighting part of word

I'm trying to build a "search in the shown elements" function with jquery and css.
Here's what I got so far:
http://jsfiddle.net/jonigiuro/wTjzc/
Now I need to add a little feature and I don't know where to start. Basically, when you write something in the search field, the corresponding letters should be highlighted in the list (see screenshot, the blue highlighted part)
Here's the script so far:
var FilterParticipants = function(options) {
this.options = options;
this.participantList = [];
this.init = function() {
var self = this;
//GENERATE PARTICIPANTS OPBJECT
for(var i = 0; i < this.options.participantBox.length ; i++) {
this.participantList.push({
element: this.options.participantBox.eq(i),
name: this.options.participantBox.eq(i).find('.name').text().toLowerCase()
})
}
//ADD EVENT LISTENER
this.options.searchField.on('keyup', function() {
self.filter($(this).val());
})
}
this.filter = function( string ) {
var list = this.participantList;
for(var i = 0 ; i < this.participantList.length; i++) {
var currentItem = list[i];
//COMPARE THE INPUT WITH THE PARTICIPANTS OBJECT (NAME)
if( currentItem.name.indexOf(string.toLowerCase()) == -1) {
currentItem.element.addClass('hidden');
} else {
currentItem.element.removeClass('hidden');
}
}
}
this.init();
}
var filterParticipants = new FilterParticipants({
searchField: $('#participants-field'),
participantBox: $('.single_participant'),
nameClass: 'name'
});
I think you're just complicating things too much... You can do this easily in a few lines. Hope this helps:
var $search = $('#participants-field');
var $names = $('.single_participant p');
$search.keyup(function(){
var match = RegExp(this.value, 'gi'); // case-insensitive
$names
.hide()
.filter(function(){ return match.test($(this).text()) })
.show()
.html(function(){
if (!$search.val()) return $(this).text();
return $(this).text().replace(match, '<span class="highlight">$&</span>');
});
});
I used hide and show because it feels snappier but you can use CSS3 animations and classes like you were doing.
Demo: http://jsfiddle.net/elclanrs/wTjzc/8/
Here`s the way to do it with jQuery autocomplete so question
If you want to build it on your own you can do the following:
1. Get the data of every item.
2. Make render function in which you will substitute say "Fir" in Fire word to Fire
3. Every time you change the text in the input you can go through the items and perform substitution.

Jquery script freezing browser but working

i'm trying to make a live search for my mobile website, I don't want to query the database every time a user type a letter so I created a ordered list with all the names that can be searched for and i'm looping through it with jquery, problem is that I have 3300 names and it's freezing the browser when it searches through them, can anyone give me a tip about better ways to do it? here is my code:
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
}
$('#pacientes_hint').html(html);
});
Use the jQuery autocomplete version. You can load an array with all your names and pass it in to autocomplete, which will work on the fly.
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
You could change your each to:
var text = $("ol.pacientes li:contains(\""+filter.toUpperCase()+"\")").map(function() {
return $(this).text();
}).join(' ');
$('#pacientes_hint').text(text);
Besides being shorter, the only improvement will be setting the contents of $('#pacientes_hint') only at the end, which could help.
Let me know if you need a more creative solution.
First of all, you could move #pacientes_hint outside the each function.
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
} // end if
}); // end each
$('#pacientes_hint').html(html);
Then, you can define ol.pacientes as a variable before the keyup handler, so it doesn't look for it everytime and in the each function, search inside the variable:
$(document).ready(function(){
var pacientes_list = $("ol.pacientes");
var pacientes_hint = $("#pacientes_hint");
$("input#search").keyup(function(){
...
$("li", $(pacientes_list)).each(function(){ // search in the container
...
}); // end each
$(pacientes_hint).html(html);

Categories