I am working with a api where i need to post a url from a form and get response. Everything is working well except one thing. I could not figure out how to get url posted in form input in to a variable for javascript. Take a look at following.
<form action="#" method="post">
<input type="text" class="url" name="url" />
<input type="submit" value="Analyse for Page Speed" value="submit" />
</form>
I use above form to get url and i want that url to be a value for the following variable
// Specify the URL you want PageSpeed results for here:
var URL_TO_GET_RESULTS_FOR = 'your url here';
How to get this done?
Is this what you're looking for?
var URL_TO_GET_RESULTS_FOR = document.getElementsByName('url')[0].value;
getElementsByName returns an array with all elements having the name passed as parameter. Since I'm assuming you have only one element with name="url", I get the first position of the array and returns the value.
As #crush pointed out in the comments, this task alone probably does not merit the use of jQuery. So if you aren't already using it, this should probably not be the deciding factor. If you need a pure JS solution, go with #ClaudioRedi's answer.
However, I'm assuming you're already using jQuery, and are asking for a jQuery solution. So here it is:
var URL_TO_GET_RESULTS_FOR = $('form input[name="url"]').val();
This will get the value of an <input> with the name url within a <form> element.
Related
I have these lines of code:
<span
class="close-modal"
onclick="#Html.Action("SaveNotes", "CallCenter", new { activityId = item.callIdKey, noteText = "test1" })">
×
</span>
Notes: <br />
<textarea name="paragraph_text" rows="5" style="width:90%">
#item.NoteText
</textarea>
I would like to replace test1 from the noteText route variable and instead change it to whatever the value in the <textarea> tag is.
Is there an elegant way of doing this without writing a giant block of jQuery code?
#Html.Action() renders a partial view as an HTML string during page processing (on the server side). It doesn't exist any more in the markup, once the page is sent to the browser. You can't do what you are trying to do this way. At the very least, I'm sure you don't want to render a partial view inside the onclick event of your <span> tag.
Why not instead use an HTML helper for the <textarea> tag? Then you can get whatever value the user typed into it on the server code. You'll want to make the form post itself back to the server on the close-modal element:
<span class="close-modal" onclick="$('form').submit()">×</span>
<form method="post" action="#Url.Action("SaveNotes", "CallCenter", new { activityId=item.callIdKey }">
Notes: <br />
#Html.TextArea("noteText", item.NoteText, new { rows="5", style="width:90%" })
</form>
This assumes you have jQuery already (a common assumption with ASP.NET). You may not need the <form> tags if you already have a form on your page.
A #gunr2171 notes in the comments, the only way to dynamically update a link once it's been rendered to the browser is via some form of client-side scripting, typically JavaScript. In your case, I'd recommend doing something like this:
<span
class="close-modal"
data-href-template="#Url.Action("SaveNotes", "CallCenter", new {activityId = item.callIdKey, noteText="{note}"})"
>
×
</span>
Note: As #HBlackorby notes in his answer, you shouldn't be using #Html.Action() here; I assume you meant #Url.Action().
This way, your JavaScript has a template (data-href-template) that it can work against with a clearly defined token ({note}) to replace, instead of needing to parse the URL in order to identify where the previously replaced text is. Otherwise, you potentially end up in a scenario where you type e.g. CallCenter into your <textarea /> and it's now an ambiguous reference that you can't just blindly replace. Or, worse, you type 'a' and it's really ambiguous.
If you are already using jQuery on your site, the actual replacement might be done using something along the lines of:
$(document).ready(function () {
$('span.close-modal').click(function() {
var noteInput = $('textarea[name="paragraph_text"]');
var encodedNote = encodeURI(noteInput.text());
var template = $(this).data("href-template");
var targetUrl = template.replace("{note}", encodedNote);
window.location.href = targetUrl;
});
});
You can also do this without jQuery, obviously—and should if you're not already depending on it. The point is to illustrate that this doesn't necessarily need to be a "giant block of jQuery code". In fact, this could be done in just a few lines—and probably should be. I deliberately broke it out into multiple steps and variables for the sake of readability.
This afternoon I experienced a very strange behavior of AngularJS.
If an expression containing "//" is in "action" attribute of a form, then the angular gives interpolate error.
Please see the code below. If you run the code, the URL can be correctly displayed in all places except in "action" attribute.
<form
id="moodleform" target="my_iframe"
method="post" action="{{'http://www.someurl.com'}}"
style="{{'http://www.someurl.com'}}"
some-attr="{{'http://www.someurl.com'}}">
{{'http://www.someurl.com'}}
<input name="somefield" value="someValue"/>
<input type="submit" value="Submit">
Here is the Plunker that demonstrates this problem, if you inspect the form element, you can see the action attribute is empty and there is error in console saying $interpolate:interr
https://plnkr.co/edit/R2ypg6WWmro1WdrNy6mX?p=preview
Any idea, thank you all.
You need to use ng-action instead of just action attribute
I found the solution.
Here is the original stackoverflow post: Angular set form action based on variable in scope
basically, i need to use $sce service in my controller in order to have an url in "action" attribute.
I have a page, showlist.php, which loads a set of results from a recordset. There is a search field which returns results using jquery load. This works fine for one word, but not if there is more than one word in the search query. Can anybody show how to get this to work for any search query? Must be some basic error but googling around has not helped.
Key elements of showlist.php:-
<div id="contentarea">
<script type="text/javascript">
function contentloader(url){
$("#contentarea").load(url);
}
</script>
<input name="search" type="text" id="inputsearch"/>
<a onclick="contentloader('showlist.php?search='+document.getElementById('inputsearch').value+'')">Search</a>
</div>
You need to HTML encode the result of document.getElementById('inputsearch').value so that all the works are passes to the server.
See:
HTML-encoding lost when attribute read from input field
Encode URL in JavaScript?
and links therein.
You need to call encodeURIComponent with the value to correctly format the query/search term:
<a onclick="contentloader('showlist.php?search='+encodeURIComponent(document.getElementById('inputsearch').value)+'')">Search</a>
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.
type abc%20xyz in the box. if that works, maybe you need to urlencode the value.
You can use onClick listener, since you are already using jQuery. I think it is a better than using onClick attribute.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<div id="contentarea">
<input name="search" type="text" id="inputsearch"/>
<a id="search">Search</a>
<script type="text/javascript">
$( document ).ready(function (){ // when document ready
$("#search").click(function(){ // add a click listner
$("#contentarea").load(
encodeURI($('#inputsearch').val()) // encode input string
);
}
);
})
</script>
</div>
I am sorry for asking such a noob question. But I saw a video very long time ago and I think it was a framework based on jquery, where if a user makes some CRUD changes to an object, the object's properties are auto updated not only for 1 user, but on all the other users browser. I am trying to find it but I am all lost! I would really really appreciate if you could help me out. Thank you!
Lets say you have a html form that looks like this
<form>
<input type="text" name="firstName" value="Jackson" />
<input type="text" name="lastName" value="Rivera" />
<textarea name="lifestory">
When i was 2yo, spot died...
</textarea>
</form>
simply add an OnChange event on every element you want to dynamicly change:
<form>
<input .. .. onchange="shareValueWithOthers(this.name, this.value)"/>
<input .. .. onchange="shareValueWithOthers(this.name, this.value)"/>
<textarea onchange="shareValueWithOthers(this.name, this.innerHTML)">
When i was 2yo, spot died...
</textarea>
</form>
Notice that a change of the elements value (or in the case of the textarea - it's contents) causes the function shareValueWithOthers(this.name, this.value) starts to run. this.name is the variable for the name, this.value is the variable for the value, this.innerHTML is the variable for the contents.
Now you have to write a Javascript function so you can send the changes to the server. Look into AJAX. Make a function that sends a POST request to your PHP script.
Your PHP script should save all the values either in a database, or in JSON-format in a file on the server. JSON is the easiest. Look into JSON PHP PARSER.
Last but not least. If you do the right thing, and make sure that every new value that a user enters gets updated in your json file by your PHP script. You can make the last step. which is to make a javascript function that retrieves the JSON file. JSON stand for JavaScript Object Notation, so your javascript can use this right away.
What you will do next, is to change all the values in your DOM that look different from the values in your retrieved JSON object.
two type of protocol, Websocket or WebRTC.
socket.io is Websocket very popular and easy.
gevent-socketio for python
Plenty base on node.js. sailsjs, deployd, meteor
I need to take the contents of form fields (client, phone number) validate them (most likely using regex) and concatenate them into an alert and a modify some html so on form submit I get
<p>John smith
99999999
2 wilerby dr
morrowie city
morrowie </p>
and alert("form data")..
I tried with something like var field1 = document.forms[0].elements[0].value,
but not sure how to address the fields.
Edit:
<form id="form1" action="form_action.asp">
<fieldset>
<table cellpadding="3" border="0">
<th> Order Details </th>
<tr>
<td>Client Name:</td>
<td><input id="clientname" type="text" name="clientname" value="" maxlength="20"></td>
</tr>
...
Edit 2
var name = document.getElementById('clientname').value;
function buttontest()
{
alert(clientname);
}
using this script I keep getting a [object HTMLInputElement] alert, the script is external and the script tag is in the header.
You should use DOM selectors alike document.getElementById('elementId').value.
Please read the resembling documentation about such browser APIs: https://developer.mozilla.org/en-US/docs/Web/API/document
Try add an ID to those fields, and use getElementById(). Example.
var val = document.getElementById('id_field').value;
document.getElementById('id_tag').innerHTML = val;
var clientName = document.getElementById('clientname').value;
alert(clientName);
if you already know the sequence no of the element that you want to address then only you can use the syntax you specified i.e. as follows:
document.forms[form_index].elements[form_element_index].value
form_index->the index of the particular form where the element is.
form_element_index->the index of the element in the particular form.
So you could use:
alert(document.forms[form_index].elements[0].value);
N.B.-form_index will be 0 only if the form you refer to is the first form in your document.
Otherwise
If you don't know either the sequence no of the form or the sequence no of the element in the form you should use the id attribute to refer to it(No need of any reference to the form where the element is) which is the usual approach and I personally suggest you to use this.
So in your code use the following:
alert(document.getElementById('clientname').value)
You should use document.getElementById('ID'), you can go to www.w3schools.com for more details.