<td valign="top"><center>
<textarea id="ta_in" rows="7" cols="42" onkeyup="get_ml()"></textarea><br>
<textarea id="ta_out" rows=7" cols="42"></textarea></center>
</td>
//javascript file.
function get_ml()
{
en = "|" + document.getElementById("ta_in").value;
ml = "";
n = 0;
.....
.....
.....
document.getElementById("ta_out").value = ml;
}
//i need to use addEvent instead of onkeyup
For modern browser compatibility, you would use addEventListener like this:
document.getElementById("ta_in").addEventListener("keyup", function(e) {
var en = "|" + document.getElementById("ta_in").value;
var ml = "";
var n = 0;
.....
.....
.....
document.getElementById("ta_out").value = ml;
});
Working demo: http://jsfiddle.net/jfriend00/6QMFV/
You would just run this code after your page has been loaded, by either placing the code at the end of your page (just before </body>) or by putting it in a function that you call from just before </body> or by calling this code for an event handler that listens for an event that tells you the page is loaded.
Related
I have some simple code that allows you to enter Amazon isbns/asins and converts them to hyperlinks. These hyperlinks are Amazon.com searches for the said isbn/asin.
Example pic: http://imgur.com/a/rYgYt
Instead of the hyperlink being a search I would like the link to go directly to the products offer page.
The desired link would be as follows:
https://www.amazon.com/gp/offer-listing/ASIN/ref=dp_olp_used?ie=UTF8&condition=used
"ASIN" would be where the ASIN/ISBN would need to be populated to generate the link, for example:
Im asking if someone could help modify my existing code to create the change. My skills lack the ability to implement the change. The existing code is as follows:
<html>
<head>
</head>
<div><b>ISBN Hyperlinker</b></div> <textarea id=numbers placeholder="paste isbn numbers as csv here" style="width:100%" rows="8" >
</textarea> <div><b>Hyperlinked text:</b></div> <div id="output" style="white-space: pre"></div>
<input type="button" id="button" Value="Open All"/>
<script>
var input = document.getElementById('numbers');
var button = document.getElementById('button');
var output = document.getElementById('output')
var base =
'https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
var urls = []
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
button.addEventListener('click', openAllUrls, false);
//function that runs when the change event is emitted
function handler () {
var items = input.value.split(/\b((?:[a-z0-9A-Z]\s*?){10,13})\b/gm);
urls=[];
// Build DOM for output
var container = document.createElement('span');
items.map(function (item, index) {
if (index % 2) { // it is the part that matches the split regex:
var link = document.createElement('a');
link.textContent = item.trim();
link.setAttribute('target', '_blank');
link.setAttribute('href', base + item);
container.appendChild(link);
urls.push(base + item);//add the url to our array of urls for button click
} else { // it is the text next to the matches
container.appendChild(document.createTextNode(item))
}
});
// Replace output
output.innerHTML = '';
output.appendChild(container);
}
function openAllUrls(){
for(var i=0; i< urls.length; i++){//loop through urls and open in new windows
window.open(urls[i]);
}
}
handler(); // run on load
</script>
</html>
to modify output URL, replace
var base = ".....';
with
var basePrefix = 'https://www.amazon.com/gp/offer-listing/';
var baseSuffix = '/ref=dp_olp_used?ie=UTF8&condition=used';
and replace
base + item
with
basePrefix + item + baseSuffix
I am trying to write a functionality for editing feature attributes through layer.bindPopup for Leaflet features. At this point I have pretty much everything I need, except of the one last thing: Documentation is saying that layer.bindPopup takes either HTML string or HTML element, so I need to concatenate my HTMLString with two elements: saveChanges button and speed_input input and then feed layer.bindPopup with it. Any manipulations with $.append did not help. Any suggestions on how to resolve this?
function onEachArc(feature, layer) {
// Create an input
var speed_input = L.DomUtil.create('input', 'speed');
// Set a feature property as value
speed_input.value = feature.properties.speed;
// Add a listener to watch for change on time input
L.DomEvent.addListener(speed_input, 'change', function(){
// Change the value of speed
feature.properties.speed = speed_input.value;
});
// Bind popup to layer with input
HTMLString = '<table style="width:100%">\
<tr style="background-color:grey">\
<th><b>Arc Numer: </b>' + feature.properties.linkstr + '</br></th>\
</tr>\
<tr>\
<td><b>Speed: </b> ' + feature.properties.speed + '.</div></td>\
</tr>\
</table>';
var saveChanges = document.createElement('button');
saveChanges.innerHTML = 'Save Changes';
saveChanges.onclick = function(){
$.ajax({
type:"POST",
url:"php/updateFeature.php",
data: {feature: feature},
success: function(data){
$('#test').html(data);
}
});
//return false;
}
};
/*
This did not help
var box = document.createElement("div");
box.style.width = "100px";
box.style.height = "100px";
$("#box").append("#saveChanges");
layer.bindPopup(box);
*/
layer.bindPopup(saveChanges);
};
You could use innerHTML:
The Element.innerHTML property sets or gets the HTML syntax describing the element's descendants.
var form = L.DomUtil.create('form', 'my-form');
form.innerHTML = '<input type="text" class="my-input" />';
var button = L.DomUtil.create('button', 'my-button', form);
button.textContent = 'Ok!';
http://plnkr.co/edit/DiK1zj?p=info
or use outerHTML:
On return, content contains the serialized HTML fragment describing the element and its descendants.
var inputHTML = '<input type="text" class="my-input" />';
var button = L.DomUtil.create('button', 'my-button', form);
button.textContent = 'Ok!';
var buttonHTML = button.outerHTML;
var form = '<form class="my-form">' + inputHTML + buttonHTML + '</form>';
http://plnkr.co/edit/Z6rADJ?p=preview
That said (and after reading your comment), i must say: this works but is very hacky. I wouldn't recommend doing this sort of thing this way. You either build your form with HTML elements or use a template/string and convert that into HTML elements so you can attach handlers and process stuff. Mixing things up will get you into trouble. I would approach it this way:
The template:
var template = '<form id="popup-form">\
<label for="input-speed">New speed:</label>\
<input id="input-speed" class="popup-input" type="number" />\
<table class="popup-table">\
<tr class="popup-table-row">\
<th class="popup-table-header">Arc numer:</th>\
<td id="value-arc" class="popup-table-data"></td>\
</tr>\
<tr class="popup-table-row">\
<th class="popup-table-header">Current speed:</th>\
<td id="value-speed" class="popup-table-data"></td>\
</tr>\
</table>\
<button id="button-submit" type="button">Save Changes</button>\
</form>';
Use a stylesheet, keeps the template nice and clean:
.popup-table {
width: 100%;
}
.popup-table-row {
background-color: grey;
}
In the onEachFeature function, attach a click handler:
L.geoJson(collection, {
onEachFeature: function (feature, layer) {
layer.on('click', layerClickHandler);
}
});
And handle it:
function layerClickHandler (e) {
var marker = e.target,
properties = e.target.feature.properties;
// Check if a popup was previously set if so, unbind
if (marker.hasOwnProperty('_popup')) {
marker.unbindPopup();
}
// Create new popup from template and open it
marker.bindPopup(template);
marker.openPopup();
// Now that the popup is open and the template converted to HTML and
// attached to the DOM you can query for elements by their ID
L.DomUtil.get('value-arc').textContent = properties.arc;
L.DomUtil.get('value-speed').textContent = properties.speed;
var inputSpeed = L.DomUtil.get('input-speed');
inputSpeed.value = properties.speed;
L.DomEvent.addListener(inputSpeed, 'change', function (e) {
properties.speed = e.target.value;
});
var buttonSubmit = L.DomUtil.get('button-submit');
L.DomEvent.addListener(buttonSubmit, 'click', function (e) {
// Do fancy ajax stuff then close popup
marker.closePopup();
});
}
Example on Plunker: http://plnkr.co/edit/8qVoW5?p=preview
This is cleaner, faster, it doesn't bind popups to every marker. It's more readable, extendable and less error prone. I hope that help, good luck!
Separating javascript and markup is easy when the script doesn't have parameters. But how is it done with inline script lines that do? Example:
<td class="input-cell">
<input type="radio" name="action-type" id="change-add" value="change-add"
onclick="showSelectTables('none','none','none','table','none','none')">
</td>
(....)
<script>
function showSelectTables(set1a,set1b,set1c,setSetup,set2,set3) {
var _1a = document.getElementById('careSelector');
_1a.style.display = set1a;
var _1b = document.getElementById('module-I');
_1b.style.display = set1b;
var _1c = document.getElementById('clarificSection');
_1c.style.display = set1c;
var setup = document.getElementById('setup');
setup.style.display = setSetup;
var _2 = document.getElementById('module-II');
_2.style.display = set2;
var _3 = document.getElementById('module-III');
_3.style.display = set3;
}
</script>
.
I've tried all varieties I can think of, but all I'm getting is error reports, 'undefined' or the silent treatment from the browser. Is it possible at all, and if so, how? I would be looking for a vanilla javascript solution.
EDIT: see here for what I'm trying to achieve: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript, section 2.
I suggest you to change your HTML generation logic to generate the followings:
<td class="input-cell">
<input type="radio" name="action-type" id="change-add" value="change-add" />
</td>
<script>
// just show 2 variables for demo
var settings = { change-add : { set1a: 'some_value', set1b: 'some_value' } }
$('#change-add').click(function() {
showSelectTables($(this).attr('id'));
});
function showSelectTables(the_id) {
var set1a = settings[the_id]['set1']; // which returns 'some_value'
// similar for set1b,set1c,setSetup,set2,set3
var _1a = document.getElementById('careSelector');
_1a.style.display = set1a;
var _1b = document.getElementById('module-I');
_1b.style.display = set1b;
var _1c = document.getElementById('clarificSection');
_1c.style.display = set1c;
var setup = document.getElementById('setup');
setup.style.display = setSetup;
var _2 = document.getElementById('module-II');
_2.style.display = set2;
var _3 = document.getElementById('module-III');
_3.style.display = set3;
}
</script>
Note: this assumes you use jQuery.
An important note: there is nothing wrong to use inline onclick, but it's a better pattern to separate JS and HTML
I had developed a LOGO-like basic turtle graphics interpreter a few years back, I wan't to put it on the web (as my cousin keeps bugging me for it). Though I am quite new to HTML, Javascript coding I thought I would give it a try & take this as a learning experience.
The below code is just for the basic UI (my UI looks very ugly and I will clean it up later).
I have written a Javascript function pushCmd which is called onsubmit of the "cmd-form".
function pushCmd()
{ var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = new String(srcElement.innerHTML);
srcText = srcText.toUpperCase();
if (srcText.indexOf("NO CODE") != 0)
{
srcText = cmdText;
}
else
{
srcText += "<br>" + cmdText;
}
srcElement.innerHTML = srcText;
}
The form is declared like below.
<div id="command-container">
<form name="cmd-form" action="" onsubmit="pushCmd()" onreset="resetSource()" method="post">
<input type="text" name="cmd-text" size="80">
<input type="submit" value="Send">
<input type="reset" value="Reset">
<input type="button" value="Run">
</form>
</div>
The pushCmd function should alter the HTML content of the div "source-container" which by default looks like below.
<div id="source-container">NO CODE</div>
After I submit the first text (say "FWD 100"). The content of the "source-container" should change to "FWD 100". Then If I submit "RT 90", the content should be "FWD 100RT 90". This is what I expect out of it.
But when I submit the text. The content of the "source-container" changes for just an instant and then again comes back to "NO CODE". Why is this happening, can anyone please point out where my mistake lies?
I tried both get & post methods but the result is the same. I cannot see any errors or warnings in the Javascript console either. I am using Google chrome Version 26.0.1410.63 if that matters (I guess not).
Please let me know if you need any further information or the full HTML source for this.
It's happening because HTML forms submit to the server by sending a new HTTP request which in your case, with the empty action attribute, is similar to refreshing the page in your browser. In order to prevent the browser from performing the default action (submitting the form) you can return false from your function, by adding return false; as a last line in it:
function pushCmd() {
var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = srcElement.innerHTML.toUpperCase();
if (srcText.indexOf("NO CODE") !== 0)
{
srcText = cmdText;
}
else
{
srcText += "<br>" + cmdText;
}
srcElement.innerHTML = srcText;
return false;
}
Then change your HTML attribute to return the return value of your function from the onsubmit:
onsubmit="return pushCmd()"
You need to return false from pushCmd, and change the onsubmit attribute to onsubmit="return pushCmd();" otherwise the form will submit itself and refresh the page.
Also, you need to change this line:
srcText = "<br>" + cmdText;
to:
srcText += "<br>" + cmdText;
This is equivalent to:
srcText = srcText + "<br>" + cmdText;
Which means that you want to append cmdText to srcText. If you don't have +=, you basically end up overwriting srcText with just cmdText.
Your form is actually submitting to the empty action. An empty action usually ends up refreshing the current page. So your page may be refreshing so fast that it appears to be an instant change of the source-container div.
Instead of using a Submit button, try type=button and then set that button's onclick in the javascript. (Note the id="" on the Send button in the HTML)
HTML
<div id="command-container">
<form id="cmd-form" action="" onreset="resetSource()" method="get">
<input type="text" id="cmd-text" name="command" size="80" />
<input type="button" id="btnSend" value="Send" />
<input type="reset" value="Reset" />
<input type="submit" value="Run" />
</form>
</div>
<div id="source-container">NO CODE</div>
Javascript
function pushCmd()
{
var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = new String(srcElement.innerHTML);
srcText = srcText.toUpperCase();
alert(cmdText);
if (srcText.indexOf("NO CODE") != 0)
{
srcText = cmdText;
}
else
{
srcText += "<br>" + cmdText;
}
srcElement.innerHTML = srcText;
}
document.getElementById('btnSend').onclick = pushCmd;
See this codepen as an example of this code: http://codepen.io/keithwyland/pen/scAJy
You're submitting the form, so the page is refreshing, setting it back to its original state.
Depending on what you ultimately need, one solution is to prevent the form submission. You can do this with a simple return false; at the end of your function.
function pushCmd() {
var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = srcElement.innerHTML;
srcText = srcText.toUpperCase();
if (srcText.indexOf("NO CODE") != 0) {
srcText = cmdText;
} else {
srcText = "<br>" + cmdText;
}
srcElement.innerHTML = srcText;
return false;
}
You are probably sending the whole page to the server which will cause it to refresh and therefore you will get the same default value back.
To prevent that from happening you can try to use AJAX, which will allow you to send data to server without refreshing the whole page.
one way to prevent your page to submit to the server is to add return false; to your function.
function pushCmd()
{ var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = new String(srcElement.innerHTML);
srcText = srcText.toUpperCase();
if (srcText.indexOf("NO CODE") != 0)
{
srcText = cmdText;
}
else
{
srcText = "<br>" + cmdText;
}
srcElement.innerHTML = srcText;
retrun false;
}
You need to return false from your onsubmit event handler to prevent the page from refreshing itself. When you push the submit button, your event handler fires but then immediately the form is submitted, which loads the page again. If you return false from an event handler, it prevents the default behavior.
function pushCmd()
{ var cmdText = document.forms["cmd-form"]["cmd-text"].value;
var srcElement = document.getElementById("source-container");
var srcText = new String(srcElement.innerHTML);
srcText = srcText.toUpperCase();
if (srcText.indexOf("NO CODE") != 0)
{
srcText = cmdText;
}
else
{
srcText = "" + cmdText;
}
srcElement.innerHTML = srcText;
return false;
}
Additionally, you'll need to return pushCmd() instead of just pushCmd() in your event handler.
I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
But in this task, firstly I try to catch that input in javascript file, and I am failing in the same. Can you tell me for this, which command will I use ?
Till now my work is :-
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT FILE:-
function addString(x) {
var val = x.name.value;
//var s = document.getElementById("name_id").getElementValue;//x.name.value;
alert(val);
}
EDITED
My New JAVASCRIPT FILE IS :-
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the string, but unable to show on the web page.
See this fiddle: http://jsfiddle.net/MjyRt/
Javascript was almost right
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
alert(s);
}
Try to use jQuery (simpler)
function addString() {
var s = $('#name_id').val();//value of input;
$('#list').append(s+"<br/>");//list with entries
}
<div id='list'>
</div>