JQuery: Append/After difficulties - javascript

I have a simple input line and want to append whatever has been entered each time somebody pushes the OK button. Sounds simple so far, still I am unable to get it working
HTML:
<p>
<input name="todo" id="todo" type="text" value="Set Me To Value" size="32" maxlength="30" />
<p id="status">Ok</p>
<br>
JQuery:
$(document).ready(function(){
$('#status').on('click', function(){
var input = $('input[name=todo]').val();
$('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>').after('#status');
});
});
I also tried my luck with append or appendTo, but both times unsuccessfully.
Just in case here is the JSFiddle: http://jsfiddle.net/NRWzE/

.after() works, but you need to set it up correctly, according to documentation it should be:
.after( content [, content ] )
So the right way is:
$("#status").after('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>');

Try use jquery insertAfter:
$(document).ready(function () {
$('#status').on('click', function () {
var input = $('input[name=todo]').val();
$('<br><b id="taskz">' + input + '</b> - <b id="statusz">Ok</b>').insertAfter('#status');
});
});

It looks like you meant to use:
$('#status').after('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>');
(see after docs)
or, alternatively insertAfter:
$('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>').insertAfter('#status');

Try this:
$('#status').click(function(){
var input = $('input[name=todo]').val();
$('#status').append('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>');
});

There are a few things going on, but the big thing is that you need to research more how after, append and appendTo work. Here's the basic syntax difference in the methods that share a name but one has To on the end:
Newcontent.appendTo(existingElement) returns newElements.
existingElement.append(newContent) returns existingElement.
Additionally, after puts the new element as a sibling of the reference element, whereas append puts the new element as a child. This is an important difference.
So, try this script then:
var taskid = 1;
$('#valueform').on('submit', function(){
var input = $('#todo').val();
$('<br><span id="task' + taskid.toString() + '">' + input
+ '</span> - <span id="status' + taskid.toString()
+ '">Ok</span>').appendTo('#status');
taskid += 1;
$('#todo').focus().select();
return false;
});
$('#todo').focus().select();
See a Live Demo at JSFiddle
Here's the supporting HTML:
<form id="valueform">
<input name="todo" id="todo" type="text" value="Set Me To Value" size="32" maxlength="30" />
<input type="submit" value="OK" id="okbutton">
</form>
<p id="status"></p>
There are some other concerns:
I recommend you study which HTML elements are allowed within which HTML elements.
Instead of putting a <b> tag on each item, use CSS. Additionally, if there is semantic importance for the bolding, then use <strong> instead. <b> also should probably not take an id because it is a presentation tag, not a content tag. When thinking of presentation vs. semantics, one must consider screen readers or browsers that cannot render bold text--in that case, <strong> will allow them to emphasize the text in another way if needed.
Get familiar with the jQuery documentation. Careful reading of what exactly each function does, the object it works on, the parameters expected, and the values returned will enable you to get past barriers in the future without having to ask here.
It looked to me like you wanted to put the new content inside of the #status paragraph, not after it. So I wrote my script that way. If you put it after the way you wrote it, then the most recent status will be on top--but then you have non block-level content (starting with your <br>) outside of any block-level element. So you should be appending <p> elements, or you should put your content inside the existing <p>.
Note: I added a form and made the button type submit instead of button to get easy Enter-key handling. It doesn't have to be this way.

Related

Create a single search box which searches two different sites using javascript

I've made multiple search boxes that search external dictionary sites. Due to the site search syntax, I've had to use JavaScript to construct a url from the text box input. This code works perfectly fine:
function prepare_link_glosbe() {
var url_param_gl = document.getElementById('url_param_gl');
var target_link_gl = document.getElementById('target_link_gl');
if ( ! url_param_gl.value ) {
return false;
}
target_link_gl.href = "https://nb.glosbe.com/en/nb"
target_link_gl.href = target_link_gl.href + '/' + encodeURI(url_param_gl.value);
window.open(target_link_gl.href, '_blank')
}
function prepare_link_dict() {
var url_param_dict = document.getElementById('url_param_dict');
var target_link_dict = document.getElementById('target_link_dict');
if ( ! url_param_dict.value ) {
return false;
}
target_link_dict.href = "https://www.dict.com/engelsk-norsk"
target_link_dict.href = target_link_dict.href + '/' + encodeURI(url_param_dict.value);
window.open(target_link_dict.href, '_blank')
}
<!--Search Glosbe.com-->
<div style="border:0px solid black;padding:8px;width:60em;">
<table border="0" cellpadding="2">
<tr><td>
<input type="text" onfocus="this.value=''" value="Search glosbe.com" name="url_param_gl" id="url_param_gl" size="40"/>
<input type="button" onclick="prepare_link_glosbe()" value="Glosbe (en-no)" />
<a href="https://nb.glosbe.com/en/nb" id="target_link_gl" target="_blank" ></a>
</td></tr></table></div>
<!--Search Dict.com-->
<div style="border:0px solid black;padding:8px;width:60em;">
<table border="0" cellpadding="2">
<tr><td>
<input type="text" onfocus="this.value=''" value="Search dict.com" name="url_param_dict" id="url_param_dict" size="40"/>
<input type="button" onclick="prepare_link_dict()" value="Dict (en-no)" />
<a href="https://www.dict.com/engelsk-norsk" id="target_link_dict" target="_blank" ></a>
</td></tr></table></div>
However, I wish to search both sites using a single input box. I've tried different approaches, including addEventListener, but I'm not fluent enough in either HTML or JavaScript to achieve it. Can anyone point me in the right direction?
First of all, some things that will make your life easier in the long run:
You don't need this.value='', just use the placeholder attribute - it's well supported.
Don't use <table> to create a layout.
Don't use attributes to assign JS event handlers. (so no onclick=)
And now, how to use just one text field for both websites - just remove the second field and move the button somewhere else. Here's an example:
// This is our search input field.
const searchValue = document.getElementById('search_value');
// Here I'm looking for all search buttons and iterating over them
// with for ... of, querySelectorAll accepts valid CSS selectors.
for (let button of document.querySelectorAll('.search_button')) {
// Getting the data-url attribute value from the button.
const url = button.dataset.url;
// Adding a click event handler, instead of relying on onclick=''
button.addEventListener('click', function () {
// Quick string replace...
const targetURL = button.dataset.url.replace('%s', encodeURI(searchValue.value));
// ...and here we open the new tab.
window.open(targetURL, '_blank');
});
}
<div>
<input type="text" placeholder="Search..." id="search_value" />
<button class="search_button" data-url="https://nb.glosbe.com/en/nb/%s">Glosbe (en-no)</button>
<button class="search_button" data-url="https://www.dict.com/engelsk-norsk/%s">Dict (en-no)</button>
</div>
Here's the explanation:
I'm using the HTML data-* attributes (accessible in JS via element.dataset.*) to store the URL, %s is being used as a placeholder for the search value and will be later replaced with the .replace function.
Instead of manually assigning IDs to buttons I've declared a class - this allows you to extend the application infinitely.
I've merged the input fields into just one and read its value in the button event handler.
I've replaced your this.value='' hack with a proper placeholder.
I've removed the table layout, if you wish to add a nicer layout or styling I would suggest to learn more about CSS - also: don't use HTML attributes to style elements (except for class and style). Avoid using ID selectors in CSS as well (it's fine in JS, but in CSS it can cause issues when it comes to importance). Also, you should avoid the style attribute anyway - it will take precedence over most CSS rules except for the rules with !important and causes code duplication.

Typeahead placing span tag after my label tag for my search. How can I add a label properly?

We have to be ADA compliant on our site. One of the things they look for is every form must have a label tag. The code has a label tag in the right place, but then when the javascript loads on the page, a span tag gets between the tag and the search field making it no longer compliant. I don't see a way to add a label. I was curious if anyone else had a suggestion for this or is there an alternative to typeahead that will work? In order to be compliant it must look like
<label for="search">Search: </label>
<input type="text" name="search" id="search"/>
For example the way it works now looks like...
<label for="search">Search: </label>
<span class="twitter-typeahead">
<input type="text" name="search" id="search"/>
</span>
There is no option to change the span tag that wraps your input. You can see where it is hardcoded in the source code here. Unfortunately, typeahead is no longer maintained either, so there will not be a future option to customize this.
However, you can always modify the code yourself. Either in the www.js file that I linked to (if you compile yourself) or in the bundle, find the buildHtml() function and change that line to an empty string.
function buildHtml(c) {
return {
wrapper: '',
menu: '<div class="' + c.menu + '"></div>'
};
}
I don't know if this will have unknown repercussions elsewhere in typeahead, but I just tried it on a page and everything seemed to be working fine.

What is innerHTML on input elements?

I'm just trying to do this from the chrome console on Wikipedia. I'm placing my cursor in the search bar and then trying to do document.activeElement.innerHTML += "some text" but it doesn't work. I googled around and looked at the other properties and attributes and couldn't figure out what I was doing wrong.
The activeElement selector works fine, it is selecting the correct element.
Edit: I just found that it's the value property. So I'd like to change what I'm asking. Why doesn't changing innerHTML work on input elements? Why do they have that property if I can't do anything with it?
Setting the value is normally used for input/form elements. innerHTML is normally used for div, span, td and similar elements.
value applies only to objects that have the value attribute (normally, form controls).
innerHtml applies to every object that can contain HTML (divs, spans, but many other and also form controls).
They are not equivalent or replaceable. Depends on what you are trying to achieve
First understand where to use what.
<input type="text" value="23" id="age">
Here now
var ageElem=document.getElementById('age');
So on this ageElem you can have that many things what that element contains.So you can use its value,type etc attributes. But cannot use innerHTML because we don't write anything between input tag
<button id='ageButton'>Display Age</button>
So here Display Age is the innerHTML content as it is written inside HTML tag button.
Using innerHTML on an input tag would just result in:
<input name="button" value="Click" ... > InnerHTML Goes Here </input>
But because an input tag doesn't need a closing tag it'll get reset to:
<input name="button" value="Click" ... />
So it's likely your browsers is applying the changes and immediatly resetting it.
do you mean something like this:
$('.activeElement').val('Some text');
<input id="input" type="number">
document.getElementById("input").addEventListener("change", GetData);
function GetData () {
var data = document.getElementById("input").value;
console.log(data);
function ModifyData () {
document.getElementById("input").value = data + "69";
};
ModifyData();
};
My comments: Here input field works as an input and as a display by changing .value
Each HTML element has an innerHTML property that defines both the HTML
code and the text that occurs between that element's opening and
closing tag. By changing an element's innerHTML after some user
interaction, you can make much more interactive pages.
JScript
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
HTML
<p>Welcome to Stack OverFlow <b id='boldStuff'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
In the above example b tag is the innerhtml and dude is its value so to change those values we have written a function in JScript
innerHTML is a DOM property to insert content to a specified id of an element. It is used in Javascript to manipulate DOM.
For instance:
document.getElementById("example").innerHTML = "my string";
This example uses the method to "find" an HTML element (with id="example") and changes the element content (innerHTML) to "my string":
HTML
Change
Javascript
function change(){
document.getElementById(“example”).innerHTML = “Hello, World!”
}
After you clicked the button, Hello, World! will appear because the innerHTML insert the value (in this case, Hello, World!) into between the opening tag and closing tag with an id “example”.
So, if you inspect the element after clicking the button, you will see the following code :
<div id=”example”>Hello, World!</div>
That’s all
innerHTML is a DOM property to insert content to a specified id of an element. It is used in Javascript to manipulate DOM.
Example.
HTML
Change
Javascript
function FunctionName(){
document.getElementById(“example”).innerHTML = “Hello, Kennedy!”
}
On button Click, Hello, Kennedy! will appear because the innerHTML insert the value (in this case, Hello, Kennedy!) into between the opening tag and closing tag with an id “example”.
So, on inspecting the element after clicking the button, you will notice the following code :
<div id=”example”>Hello, Kennedy!</div>
Use
document.querySelector('input').defaultValue = "sometext"
Using innerHTML does not work on input elements and also textContent
var lat = document.getElementById("lat").value;
lat.value = position.coords.latitude;
<input type="text" id="long" class="form-control" placeholder="Longitude">
<button onclick="getLocation()" class="btn btn-default">Get Data</button>
Instaed of using InnerHTML use Value for input types

Javascript select element with complicated ID

need some help! am trying to get the value of the below input id "j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" and have tried jquery and javascript such as: document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:3:j_id63") but keep getting a null result. ID can't be changed either, any help appreciated
<td class="sf42_cell_bottom_light"><span id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61"><input id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" maxlength="200" name="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" size="20" type="text" value="717474417"></span></td>
Use this:
$("[id='j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61']")
By the way, since you are apperently using JSF, this is a good practice to set id to each component to avoid such horrible ids (who can changes if you add/remove components).
See more information in this thread:
Handling colon in element ID with jQuery
Do you have any control of the element? Can you add a class to it?
var val= document.getElementsByClassName("TheClassName");
Or you can get the TD with class sf42_cell_bottom_light (if it is unique) then get its INPUT elements by:
var theTd= document.getElementsByClassName("sf42_cell_bottom_light");
var val = theTD.getElementsByTagName("INPUT");
I need to see more of the HTML to give you an better answer.
You may need to escape colon in your id .So
try this
function RemoveInvalidCharacter(myid) {
return '#' + myid.replace(/(:|\.|\[|\])/g, "\\$1");
}
And call like this
$(RemoveInvalidCharacter('j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61'));
Have a look at How do I select an element by an ID that has characters used in CSS notation
I have tested this code:
<td class="sf42_cell_bottom_light">
<span id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61">
<input id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" maxlength="200" name="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" size="20" type="text" value="717474417">
</span>
</td>
<script type="text/javascript">
document.write(document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63").value);
</script>
in FF, IE, Chrome (the latest versions)... and seems to work ok... ar you sure it is about this id?
Replace:
document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:3:j_id63")
with
document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63")
The id is different.
http://jsfiddle.net/wNePW/

jquery before() is out of order?

I have a page where you can click a link that says "add a keyword" and an input will appear and you can enter the keyword, and then convert it into a span tag on blur or the "return" key. However, I've been adding onto it to allow for an "autocomplete" feature, so I'm trying to insert a
<ul></ul>
after my input in order to do a .load inside the list.
The relevant code I have is:
var addKeywordId = 0;
$('a.add_keyword').live('click', function(){
$(this).before('<input type="text" class="add_keyword" id="addKeyword'+addKeywordId+'" /><ul><li>hi</li></ul>');
$('.add_keyword').focus();
addKeywordId++;
});
The problem is, that my HTML structure ends up looking like this:
<ul><li>hi</li></ul>
<a class="add_keyword">+ add keyword</a>
<input id="addKeyword0" class="add_keyword" type="text />
INSTEAD OF
<input id="addKeyword0" class="add_keyword" type="text />
<ul><li>hi</li></ul>
<a class="add_keyword">+ add keyword</a>
Anybody know why my HTML is added out of the order I specified??
Thanks
EDIT: This seems to be working fine in Google Chrome, but not in Mozilla Firefox.. :(
This is likely due to the weird rejiggering of code Firefox does to try to display things even when there are errors. I've seen it where I miss a closing div, IE freaks out (as it should) and Firefox looks fine, as it ignores that you missed adding the ending div and guesses.
You could try a 2 stage thing. I would add an id to the ul tag, then add the input before it.
$(this).before('<ul id="ulid"><li>hi</li></ul>');
$('#ulid').before('<input type="text" class="add_keyword" id="addKeyword'+addKeywordId+'" />');
Happy haxin.
_wryteowl

Categories

Resources