I am sure this is a simple question.
To begin really playing with javascript and understand it I need to have the environment to see what my output is. I have done lessons in javascript but need to actually get the HTML and javascript talking.
What I am looking to do:
Have a user input information into an text box and have it show the result in the html.
is the sky blue? Yes (makes true be displayed on my HTML)
is the sky blue? No (makes false be displayed in my HTML)
currently i have no idea if my javascript is doing anything!
Here is my code:
HTML:
<form action="" onsubmit="return checkscript()">
<input type="text" name="value">
<input type="submit" value="Submit">
Javascript:
function checkscript() {
for (i=0;i<4;i++) {
box = document.example.elements[i];
if (!box.value) {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
return false;
}
}
return true;
}
document.write(box);
I am so confused but need to see the results of what i am doing to see where to fix things, i tried using console in chromes inspect elements function but this has confused me more.
Can someone help and clean the code up to make sense by labelling everything as what they do?
box? check script?
Thanks :)
I updated the jsfiddle I had made for you. It's a working version that might get you started.
HTML
<!-- I avoided all the mess of forms, since that submits to a server, and that's more than you want right now. Note that I added ids to each input. Ids make it very easy to access the elements later. -->
<input type="text" name="value" id="fillIn">
<input type="button" value="Submit" id="button">
JS
// My methodology here is totally different, since I directly get the element I care about
function checkscript() {
// find the element in the DOM
var box = document.getElementById("fillIn");
// check for a value
if (box.value) {
// if there is one, add a new div. That's probably not what you'll want in the long run, but it gives you something to work with (and seems to match your old idea of using document.write. I have never yet used document.write, though others with more experience than I may like the concept better.
// This creates a new element. If you press F12 and look at this in your debugger, you'll see it actually appear in the HTML once it's appended
var newElement = document.createElement("div");
// Set the value to what you want
newElement.innerHTML = box.value;
document.body.appendChild(newElement);
} else {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
// No returns necessary, since we're not dealing with formsubmittal.
}
}
// This hooks up the function we just wrote to the click event of the button.
document.getElementById("button").onclick = checkscript;
This may or may not be what you want, but it's at least a place to get started.
A few things to start out:
1.) Make sure all elements have end tags
<input type="text" name="value" />
Note backslash at end of tag.
2.) You are using a form tag, which submits a form to a server side component.
Suggest you need to use the onclick event. Which is available on all input controls. Suggest you start with buttons so:
<input type="text" name="value" onclick="myFunction()" />
<script type="text/javascript">
function myFunction() {
document.write("Hello");
console.log("Hello");
}
</script>
Writes stuff directly to the html and console. Hope that gets you started.
Regards,
Andy
Related
I am currently doing something similar to StackOverflow's system that shows how an answer will look when Markdown is converted to HTML. The part of HTML that is related to this question is
<form method='post' class='form-horizontal' role='form'>
{{csrf_field()}}
<textarea name="question" id="test" data-iconlibrary="fa" data-provide="markdown" spellcheck='false' rows="10" data-hidden-buttons="cmdPreview cmdHeading cmdCode"></textarea>
<div id='result' style='border:1px solid grey; border-radius:5px;'></div>
<input type='submit'>
</form>
And also jQuery
$('textarea[name=question]').keyup(function() {
$.post('{{url("web/questions/showPost")}}',{question:$(this).val(),_token:$('input[name=_token]').val()},
function(result) {
$('#result').html(result);
});
//DOES NOT WORK
var parentEls = $( "img" ).parents()
.map(function() {
return this.id;
}).get().join(", ");
alert(parentEls);
});
As you can see, I do $.post request to my Laravel method and get converted to HTML Markdown from there. Everything works just perfectly. What I am actually trying to do is to add img-responsive bootstrap classes to all images that are inside of my results div div#result.
I know that the easiest way to do this would be simply editing PHP converter I use (GrahamCampbell/Laravel-Markdown) and add things I want, but because I use Laravel it is a really bad idea to edit vendor files because after an update everything will be lost. So, my idea is to somehow add that class img-responsive with jQuery. It first looked simple, because I thought I can do everything with simple div p img selector, but then I realized that users need a more flexible system that will add that class even if they write something like div p a strong em img. So, my first idea was to get all parents from all img tags and check, if there is a parent whose id is result, and this was what I was trying to do under that comment //DOES NOT WORK. Actually, there I was trying only to get parents list (I think I would have fixed everything if I got it), but this code only returns me the first img parents – so, my logo's parents....
Maybe anyone knows, what could I do to add that class or how to get that parents list? Not only my solution, other solutions will be greatly appreciated (I believe there is a lot better solution than mine to add that class). If you know the solution with Laravel too, without editing vendor, this is even better.
Sorry, if I have missed an answer to my question. My English does not let me to formulate the question in a short way.
Thank you for your help.
EDIT:
The only way I could make it work (thanks to guys who commented on my post because they pointed out the problem!) was to make an additional hidden div in which I store the data I get from PHP, and then on delay add classes to img and only then put in visible div. Also, because it is reaaaally slow, I decided to do update not on keyup, but when preview button is clicked. So thats my code now
$(document).on('click','#preview',function() {
$.post('{{url("web/questions/showPost")}}',{question:$('textarea[name=question]').val(),_token:$('input[name=_token]').val()},
function(result) {
$('#hiddentResult').html(result);
setTimeout(addImgResponsive,100);
});
});
function addImgResponsive() {
$('#hiddentResult').find('img').addClass('img-responsive');
$('#result').html($('#hiddentResult').html());
}
Is there a way to fix it without using additional div? The answer why I am using a delay is because $('#hiddentResult').find('img').addClass('img-responsive'); executes too early...
So, the problem was that this guy
$('#hiddentResult').find('img').addClass('img-responsive');
worked synchronously with this one
$.post('{{url("web/questions/showPost")}}',{question:$('textarea[name=question]').val(),_token:$('input[name=_token]').val()},
function(result) {
$('#hiddentResult').html(result);
});
and executed first, before the second one got the results from PHP, I didn't see any effect because no data was loaded. After adding this function
function addImgResponsive() {
$('#hiddentResult').find('img').addClass('img-responsive');
$('#result').html($('#hiddentResult').html());
}
and putting it into setTimeout(addImgResponsive,0); to make it work asynchronously, everything now works well. Thank you, Roamer-1888 and RAHUL S R
EDIT:
My whole solution looks like that:
jQuery:
$(document).on('click','#preview',function() {
$.post('{{url("web/questions/showPost")}}',{question:$('textarea[name=question]').val(),_token:$('input[name=_token]').val()},
function(result) {
$('#hiddentResult').html(result);
setTimeout(addImgResponsive,0);
});
});
function addImgResponsive() {
$('#hiddentResult').find('img').addClass('img-responsive');
$('#result').html($('#hiddentResult').html());
}
HTML:
<form method='post' class='form-horizontal' role='form'>
{{csrf_field()}}
<textarea name="question" id="test" data-iconlibrary="fa" data-provide="markdown" spellcheck='false' rows="10" data-hidden-buttons="cmdPreview cmdHeading cmdCode"></textarea>
<div id='result'></div>
<div id='hiddentResult' class='hidden'></div>
<input type='submit'>
<input type='button' id='preview' value = 'Peržiūrėti'>
</form>
Its probably something basic but wanted explanation of the use cases. Like sometimes hitting "enter" inputs the data, while sometimes mouseclicks work. I'm concerned about "Gotchas" that I would have overlooked. Like maybe it works in Firefox but not in Chrome for example.
I saw the following 2 ways, both are ways to input data into a form element.
First way
JavaScript
var $body = $(e.target).find('[name=body]'); //defines the content
var comment = { body: $body.val() };
HTML
<form class="form-send-message" id="addcomment" data-keyboard-attach>
<textarea id="body" name="body"></textarea>
</form>
Second way
JavaScript
var message = template.find('input').value;
HTML
<form class="message" data-keyboard-attach>
<input type="text" name="body" id="body">
<button class="icon" type="submit"></button>
</form>
Here you can see two ways to find the value of an input/textarea with an explanation:
'submit .new-post': function(event){
//returns name="postBody" content from the form you're submitting
var postBody = event.target.postBody.value;
//returns the value of an html element that exists in DOM, even if its inside a different template or form.
var postBody = $('.someClass').val()
}
Your first code Is jQuery, while your second code is Meteor. They both can accomplish the same thing under the right circumstances. Also, according to this answer, meteor's template.find is an alias for jQuery's $, meaning they are the exact same.
But, the codes don't do the same thing in this case.
Your first code finds the value an element with a name of "body" inside e.target. I am assuming e is an Event, but there is no way to tell with the current amount of code you gave.
The second code just gets the value of the first INPUT element it finds.
I have created a very simple editor that has been working great. However, I just tried to put JavaScript into it and I can't get it to work.
The code for the editor:
<div id="buttoncontainer">
<input id="button" onclick="update();" type="button" value="Update page">
</div>
<div id="tryitcontainer">
<textarea id="codebox"></textarea>
<iframe id="showpage"></iframe>
</div>
The JavaScript for the editor:
<script>
function update() {
var codeinput = document.getElementById('codebox').value;
window.frames[0].document.body.innerHTML = codeinput;
}
</script>
I just wanted to run some simple JavaScript that changes an image when it is clicked. This code works fine when I run it in a full browser, so I know its the editor thats the problem.
Is there a simple fix for this that I'm missing?
The button is not finding the update() method. You need that function to be globally available:
http://jsfiddle.net/t5swb7w9/1/
UPDATE: I understand now. Internally jQuery basically evals script tags. There's too much going on to be worth replicating yourself... either use a library to append, or eval the code yourself. Just a warning that eval'ing user input is rarely a good thing and is usually a welcome mat for hackers.
window.myScope = {
update: function() {
var div = document.createElement('div'),
codeinput = document.getElementById('codebox').value,
scriptcode = "";
div.innerHTML = codeinput;
Array.prototype.slice.apply(div.querySelectorAll("script")).forEach(function(script) {
scriptcode += ";" + script.innerHTML;
div.removeChild(script);
});
window.frames[0].document.body.appendChild(div);
// hackers love to see user input eval'd like this...
eval(scriptcode);
}
};
And then you would update your button like so:
<input id="button" onclick="myScope.update();" type="button" value="Update page">
Or, even better, use addEventListener and forget the onclick part altogether. I'll let you do that research on your own ;)
JavaScript inserted via innerHTML will not be executed due to security reasons:
HTML5 specifies that a <script> tag inserted via innerHTML should not execute.
from MDN: Element.innerHTML - Security considerations, see also: W3: The applied innerHTML algorithm.
A possible solution using the jQuery method .append() works around that, as it somehow evals the content. But this will still not solve your problem, as the JavaScript code is executed in the current scope.
Here's a test scenario:
function update() {
var codeinput = document.getElementById('codebox').value;
$(window.frames[0].document.body).append(codeinput);
}
Try it here
Try to insert this script:
<script>
alert( document.getElementById('tryitcontainer') );
</script>
and this one:
<p id="test">Test</p>
<script>
window.frames[0].document.getElementById('test').innerHTML = 'updated';
</script>
The first one will return a [object HTMLDivElement] or similar. Here you can see, that you're still in the same scope as the parent frame. The second one will correctly update the content within the iframe. Keep that in mind, when experimenting with those things.
Maybe Executing elements inserted with .innerHTML has some more infos for you.
The following var is only working in my script when the text is hard coded in the textarea (e.g. London):
script
var thought = $('textarea[name=search]').val(); //...used in object literal
html
<textarea rows="5" name="search" type="text" id="term">London</textarea>
I'd like to be able to type a search term into the textarea and search for it but it's not working?
I've tried all of the answers below with no luck!? I've therefore included the following in the object literal. It pulls the hard coded value from the textarea (like before) but it doesn't pull a value that is typed in the textarea normally? I thought this might be easier to resolve the problem (the feed not working when the search term is typed in)
search: $('textarea[name=search]').val(),
I'm following this tutorial below for a twitter feed with jquery but adding a textarea to search for terms,topics,hashtags etc is proving difficult to figure out.
Twitter Feed with Jquery linky
Do with keyup or change event of textarea
$("textarea[name='search']").keyup(function(e){
var currentText=this.value;
});
You have a couple options, either search using a click event on some button called Search, or use a change / keyup event to grab the new value each time the field is updated, and perform the search that way:
$("#term").keyup(function() {
console.log(this.value); //theres your value!
});
As stated before, if you use it like this, it will be stored in the thought var and you can call it from whatever function you're using.
Since your method calls it one time probably before you edit it.
At least that is what I'm guessing since your code is obviously not complete ;).
var thought = '';
$('textarea[name=search]').keyUp(function(){
thought = $(this).val();
});
Just add jquery and use below code.
<html>
<head>
//import jquery here
<script>
$(document)
.on("click", "#btn", function(event) {
var thought = $('textarea[name=search]').val();
alert(thought);
});
</script>
</head>
<body>
<textarea rows="5" name="search" type="text" id="term"></textarea>
<input type="button" id="btn" value="click me">
</body>
hope that title makes sense. I'm a noob at javascript. What I want to do is have a form which will have a couple of inputs like, name and url for example.
When the user enters their name, I'd like the url input to automatically have as a default their name with an underscore between words. So if they type in as their name pedro kinkybottom then automatically set as the default in the url input would be pedro_kinkybottom.
I'm using cakephp if anyone happens to know a particularly cakey way to do this that'd be cool but otherwise any help at all would be most welcome.
Thanks,
Pedro
You'd probably want to do this in JavaScript and not in PHP. Even though you may be more familiar with the latter, the user experience would be better with the former and the overall design simpler (since the page wouldn't need to refresh).
You essentially need to do two things:
Set the value of an input in response to an event on another input.
Replace space characters with underscore characters.
For the second part, take a look at JavaScript's replace function. It's pretty robust and lets you do a lot of string manipulation. Definitely worth trying it out yourself.
For the first part, here's an example with jQuery:
$('#inputName').change(function() {
$('#inputURL').val($('#inputName').val());
});
This would set the value of inputURL to the value of inputName any time the value of inputName changes. For the string replacement, you'd modify it similar to this:
$('#inputName').change(function() {
$('#inputURL').val($('#inputName').val().replace(' ', '_'));
});
Note that the change event will be fired when the control loses focus. If you want to to happen as-you-type then try the keyup event. There are other events as well.
Add a keyup event to the name field that will update the url field:
<form>
<input type="text" id="name" />
<input type="text" id="url" />
</form>
...and the js:
addEvent(document.getElementById('name'), 'keyup', function () {
document.getElementById('url').value = this.value.replace(' ', '_');
});
function addEvent(ele, evnt, funct) {
if (ele.addEventListener) // W3C
return ele.addEventListener(evnt,funct,false);
else if (ele.attachEvent) // IE
return ele.attachEvent("on"+evnt,funct);
}
http://jsfiddle.net/XKEh5/
If you're only going to do some trivial stuff like this, then you'll be fine with plain old javascript. If you're going to be doing a lot of this sort of thing, plus any effects like fading out elements or whatnot, I suggest you look in to mootools or jQuery.
Here is an edited version of the above answer. There was an issue with the "value.replace(' ', '_');" where it would only take the space out between the first two words typed in. This code snippet below does it for all.
<script language="javascript" type="text/javascript">
addEvent(document.getElementById('name'), 'keyup', function () {
document.getElementById('url').value = this.value.split(' ').join('');
});
function addEvent(ele, evnt, funct) {
if (ele.addEventListener) // W3C
return ele.addEventListener(evnt,funct,false);
else if (ele.attachEvent) // IE
return ele.attachEvent("on"+evnt,funct);
}
</script>