Coffee script access to input value - javascript

I am new to javaScript, coffee script, jQuery and the UI tech in general. I am trying to accomplish really simple thing - read a value from the input field but so far with no luck. My code is pretty simple:
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" value="Hello">
</div>
From coffee script I am trying to read the value as follows:
jQuery ($) ->
$field = $('.ui-widget input')
text=$field.val
alert #{ text }
But so far with no luck, but contrary via $field.val("Bye") works just fine.
Could someone please put some shed on that?
Thx

Parameter less function calls require parentheses.
text=$field.val
Is translated to
var text;
text = $field.val;
Notice that you are getting a function reference to val
Adding the parans:
text=$field.val()
Becomes
var text;
text = $field.val();
Returning the result of the function rather then the function itself.

Related

How can I retrieve an HTML form value and put it in a JavaScript object?

so I'm kind of a beginner at JavaScript and APIs, things like that. I want to implement an API into my website that can detect whether an article is fake news or not based on the title. I already found the API, which is this, but I'm a bit confused with how to retrieve the form value from my HTML code, shown below:
<input type="text" name="check" id="check">
<button onClick="checkFakeNews" id="btn">Check</button>
<p id="result"></p>
I already tried typing up this function:
function checkFakeNews() {
document.getElementById('check') = text
console.log(text)
}
to try to print out the value, but I didn't get anything.
I also want to get the result, stored in 'data' in the API I believe, and display it in the paragraph. I'd be very grateful to anyone who can help me!
Firstly, You are you writing document.getElementById('check') = text which doesn't do anything.
Second thing that in HTML onClick need to be equal to Function Call you are passing just the Name. You need checkFakeNews() instead of checkFakeNews
This should work as required.
function checkFakeNews() {
const input = document.getElementById('check');
const text = check.value;
console.log(text);
}
<input type="text" name="check" id="check">
<button onClick="checkFakeNews()" id="btn">Check</button>
<p id="result"></p>
https://www.javatpoint.com/document-getElementById()-method , and see https://www.w3schools.com/jsref/prop_text_value.asp
var s = document.getElementById("element").innerHTML; //to set
document.getElementById("myText").value = "Johnny Bravo"; to set

parse <script> tag with js/jQuery

I have a HTML page where a user is able to edit a HTML resource (using ACE Editor). Within this HTML source, there is a <script>-tag, which does some pretty basic stuff.
Is there any elegant solution to parse the script tag in order to (e.g.) evaluate the variables used within the script tag? For "normal" tags I use parseHTML() to have the html as a jQuery object.
From this example, I would like to retrieve the value of $myVal (which is "f00") and write it to #myLabel:
<textarea id="myScript" rows="5" readonly>
<script>
$myVal = "f00";
</script>
</textarea>
<label id="myLabel">Hello</label>
$(function(){
$scriptVar = $('#myScript').text;
// parse the $scriptVar
// retrieve the value of, $myVal, write it to #myLabel
//$myParsedValue = ???
//$('#myLabel').text('bar!');
});
And here is the fiddle: https://jsfiddle.net/stepdown/jqcut0sn/
Is this possible at all? I don't really care about vanilla js, jQuery, regex or maybe even an external library for that purpose.
Thanks to #JeremyThille, who pointed me to the right direction. I found out, what I want to achieve is possible through jQuerys $.globalEval() - see the official documentation.
Basically what globalEval() does: it runs the script which is written in the <textarea> and makes the variables / functions globally accessible.
IMPORTANT: this implies, that syntax errors (etc) by the user will break the evaluation, and sequential functionality could be flawed. Also, the new variables are GLOBAL, so basically a user could rewrite scripts on the hosting page. (In my case both problems are of minor importance, since this is an internal application for trained users - they also have syntax highlighting through the amazing ACE editor. But I wanted to make sure to point it out. Also, there are several articles regarding the risks/ouch-moments when using eval()...)
I updated the fiddle to achieve what I wanted: https://jsfiddle.net/stepdown/Lxz7q6uv/
HTML:
<textarea id="myScript" rows="5" readonly>
$myVal = "f00";
</textarea>
<hr />
<label id="myLabel">Hello</label>
Script:
$(function(){
var myScriptContent = $('#myScript').text();
$.globalEval(myScriptContent);
console.log($myVal);
$('#myLabel').text($myVal);
});

(VB) Passing a textbox value with a Url.Action via javascript

In VB, I am working on an MVC project. I have a text box to enter some search criteria, and a button next to it that upon pressing will submit the value of the text box. Html Snippet:
<input type="text" id="mySearchField" />
<button onclick="location.href='#Url.Action("Search", "Movies", New RouteValueDictionary(New With {.searchCriteria = document.getElementById('mySearchField') }))'">Search</button>
My question revolves around the final part:
New RouteValueDictionary(New With {.searchCriteria = document.getElementById('mySearchField') }))'"
The code above does not work or compile, but this is my general idea of what I am attemping to do.
I want to pass the value of the text box along into the Movies/Search function, however I am at a loss as to how to format the line to mix the html, asp, and javascript all at once.
My VB Function for clarity:
Function Search(searchCriteria As String) As ActionResult
Return View()
End Function
Any advice is much appreciated!
This should be pretty close. This has jQuery as a prerequisite. To make this maintainable (you can do this, or not), I'd use NewtonSoft.Json to serialize the URL to Javascript properly, and url-encode the text box value.
<input type="text" id="mySearchField" />
<button id=myButton>Search</button>
<script>
var url = '#Html.Raw(Url.Action("Search", "Movies"))';
$("#myButton").click(function(){
location.href = url + '?searchCriteria=' + $("#mySearchField").val()
});
</script>

use eval to evaluate a javascript snippet in a textarea?

I'm at my first hackathon and trying to finish my project. I am very very new the javascript... everything I know I literally learned in the last 2 hours. That being said...
So I know that eval is not the greatest thing to use, but I'm trying to write a simple program in which you can input a javascript snippet into a textarea, click an execute button, and have the javascript execute inside another textarea. I'm trying to stay away from jquery for now, because I want to get the really basic idea down before I add another level of complexity, which is why I'm not using id's.... but if jquery is the only way to do this, then I guess I'll have to pony up and learn it in the next 8 hours.
Code as follows (ish):
function executeJS ()
{
var result = eval(game.input.value);
game.execute.value=result;
}
<head>
<body>
<H1>PRogram</H1>
<form name="game">
<textarea name="execute" rows="5" cols="30" value=""></textarea><br>
<textarea type="text" name="input" rows="10" cols="30" value=""></textarea>
<input type = "button" value = "guess" onclick = "executeJS()</input>
</form>
</body>
</head>
I'm not getting an output in my execute box.
Any insight would be much appreciated.
"game" isn't a variable. it's a DOM element name.
if you want to get it's object, give it an id let's say "game", and use document.getElementById('game')
Note that your <head> surround the <body>
Your javascript code isn't inside <script></script tag.
Here is a working version. However, I would reconsider your idea of not using IDs or libraries:
function executeJS() {
var game = document.forms['game'];
var result = eval(game.input.value);
game.execute.value = result;
}
And be wary of eval.

Is it possible to duplicate the native behavior of JavaScript's prompt()?

I'm rolling my own version of prompt() for aesthetic purposes; it's come along quite nicely as far as visuals go, but I have run into a slight hitch: the native version of the function causes code execution to cease completely until the prompt has been dealt with.
This is positively lovely and it's why the below works the way it does:
<script>
var c = prompt('Name?', '');
alert(c); // displays whatever the user entered
</script>
With my method, however, things do not go as smoothly. I am using a dialog, an input box, and an OK button to gather the data from the user; to my knowledge, data collection works perfectly; that is, I know for sure that after the user presses the OK button, I have access to the data they just put into the prompt.
I cannot, however, find a way to get my version to work as the native one does. My question, then, is this: is it at all possible to tell JavaScript to halt executing until you've told it to resume?
Thanks in advance for any and all assistance.
No, it is not possible to duplicate this behavior. The way to achieve the same effect is to use a callback in your code, so you can do something like:
myPrompt('Hello, mate, whats yer name?', function(answer) {
alert(answer);
});
EDIT: Based on your code, why not do this?
<body>
<div id="prompt" style="display: none;">
<input type="text" id="q" /> <input type="button" value="OK" id="ok" />
</div>
<script>
$ = function(i) {return document.getElementById(i);}
_prompt = function(prompt, callback) {
$('prompt').style.display = '';
$('q').value = '';
$('ok').onclick = function() {
callback($('q').value);
}
}
_prompt('Name?', function(answer) {
alert(answer);
});
</script>
</body>
If you change alert(answer); to say... gAnswer = answer; (notice no var declaration) you would be creating a global variable named gAnswer that you could access anywhere else in the javascript code, assuming the prompt was already answered. If you're concerned of global variables polluting your space you could wrap it all in a closure, but it should be fine otherwise.
#Paolo:
This is the code I am currently working with:
<body>
<div id="prompt" style="display: none;">
<input type="text" id="q" /> <input type="button" value="OK" id="ok" />
</div>
<script>
$ = function(i) {return document.getElementById(i);}
_prompt = function(q, e)
{
$('prompt').style.display = '';
$('q').value = '';
$('ok').setAttribute('onclick', e + ' $("prompt").style.display = "none";');
}
var c; _prompt('Name?', 'c = $("q").value;');
alert(c);
</script>
</body>
Now, as would be expected, that alert() fires as soon as the page is loaded, which is most definitely not what I want; ideally, I'd like for the rest of the code to wait for the prompt to get handled, but I'm strongly doubting this is possible outside of the native implementation. Reckon I'll just have to settle for designing my algorithm so that the prompt gets used immediately?

Categories