Add parameters to url with onSubmit using a Javascript function - javascript

I want to add html parameters to the url with onsubmit. I have 2 forms(1 GET, 1 POST), want to use 1 button to submit them both(Using the POST form button) When the submit button is pressed use onSubmit to call a javascript function, where parameters are "appended" to the url.
I was thinking about doing something like this:
function onSubmitForm() {
url = "localhost:8080/test/index.php?Title=document.getElementsByName('title')[0].value";
//I don't know how to actually call the url.
}
EDIT
I got what I wanted:
Appending form input value to action url as path

First, you have to concatenate the string's static and dynamic parts. Then, you can redirect.
function onSubmitForm() {
window.location = "localhost:8080/test/index.php?Title=" +
document.querySelector('title').textContent;
}
NOTES:
Only form fields have a .value property. If you are trying to get
the text within an element, you can use .textContent.
.getElementsByName() scans the entire document and makes a
collection of all the matching elements. That's wasteful when you
know you want only the first one and, in the case of <title>, there
is only ever going to be one of those in a document anyway. Use
.querySelector() to locate just the first matching element.

ES6
NOTES :
Don't forget to use Babel for converting your code in ES5.
I purpose to you this solution :
function onSubmitForm() {
window.location = `localhost:8080/test/index.php? Title=${document.querySelector('title').textContent}`
}
This way of doing with backtick is even simpler than in ES5, let me explain, before we had to concatenate with the sign + ourVariable + the continuation of our string of character.
Here we have more of that. And we can write on several lines as well.
Then ${} is used to pass a variable inside
Documentation if you want : Literal template string

Related

Creating custom spell checking for html

Is it possible to use some custom functions for spell checking in html inputs? For example I have an input where values are divided by spaces (or commas, doesn't matter) and a function which receives tokens from it. That function decides if token is spelled correctly (in my case there would be some regular expression) and returns true/false value and based on that some words would be underlined. In my head it looks something like this:
<input type="text" onCheck="checkToken">
<script>
function checkToken(token) {
const oneCrazyRegex = /[a-b]/;
return oneCrazyRegex.test(token);
</script>
Or taking whole input:
function spellCheckInput(line) {
// line is an array of tokens
return line.map(tok => checkToken(tok));
}
Is it possible to do with js/css/html or not?
P.S. onCheck is example only, I know that this attribute is not valid
Yeah you can use regex for cleaning up text but you have to remember that people can fabricate any kind of input they want since the checks would be happening client-side, and anyone can just pop open a console and send anything they want.

HTML Append Variable to Query String

I have http://localhost/?val=1
When I click on a link, is there a way this link can append a query variable to the current string, for example:
Link
so when I click it the url would be:
http://localhost/?val=1&var2=2
but when I click the link it removes the first query string and looks like
http://localhost/&var2=2
Is such a thing possible with normal HTML?
You can't do that using only html, but you can do it with js or php:
Using JS:
<a onclick="window.location+=((window.location.href.indexOf('?')+1)?'':'?')+'&var2=2'">Link</a>
Using Php:
Link
Notice 1: make sure you don't have the new variable in the current link, or it'll be a loop of the same variable
Notice 2: this is not a professional way, but it could work if you need something fast.
Basically you want to get your current URL via JavaScript with:
var existingUrl = window.location.href; // http://localhost/?val=1
Then append any Query Strings that are applicable using:
window.location.href = existingUrl + '&var2=2';
or some other similar code. Take a look at this post about Query Parameters.
Note: A link would already have to exist with an OnClick event that calls a function with the above code in it for it to work appropriately.
Now obviously this isn't very useful information on it's own, so you are going to want to do some work either in JavaScript or in Server code (through use of NodeJS, PHP, or some other server-side language) to pass those variable names and their values down so that the button can do what you are wanting it to do.
You will have to have some logic to make sure the query parameters are put in the URL correctly though. I.E. if there is only one query param it's going to look like '?var1=1' and if it's any subsequent parameter it's going to look like '&var#=#'.

How to pass javascript url parameter in this script through html dom?

I want to pass url parameter through html dom. This is the javascript i am using
<script>
function myFunction(url)
{
setTimeout(function(){window.location.assign(url)},4000);
}
</script>
HTML
Click here
But its not working. How can i fix this situation ? Thanks for your answers.
Use combination of single and double quotes, to pass the url as string literal. If the url is not enclosed in quotes it is considered as some variable and javascript could nod find that.
Click here
As #Adil says, you need to pass the argument as string to the function. In the way you are trying, the script is trying to recover the value of the http://stackoverflow.com variable.
what #Adil has said is true:
Click here
but if you want to pass the url as a parameter do not forget to change your function like this:
function myFunction(url)
{
setTimeout(function(){window.location.assign(encodeURIComponent(url)},4000);
}

invalid javascript parameter

so i have this button, which is added dynamically in java script, but the thing is a want to send the files name as a parameter to the function, i already have the name in a var saved as file, the name is generally something like p164.epub. but for some reason it wont accept the parameter. if for instance i add a number instead of file, it accepts it and it works as it should
$('#result2').append("<button class ='removeBtn' onclick ='removeEbook("+file+")'>Remove</button>");
my function
function removeEbook(n)
{
alert("yay");
}
any thoughts?
You have jQuery - don't use inline event handlers:
var file = '...';
$('<button class="removeBtn">').text('Remove').on('click', function() {
// NB: "this" refers to the clicked button
removeEbook(file);
}).appendTo('$#result2');
If you insist on using inline event handlers (and you really shouldn't), best practise is to use single quotes for your JS strings, and double quotes for the attributes within your HTML, e.g.:
$('#result2').append('<button class="removeBtn" onclick="removeEbook(\''+file+'\')">Remove</button>');
Note that as written this will bind the handler to whatever value file has at the time the handler is registered (because the code above turns it into a string constant) instead of whatever value it has when it's triggered.
Note that if file happens to contain any quote characters (which is perfectly legal on some systems) you will end up with an illegal string constant.
The above are just two of the many reasons why inline event handlers shouldn't be used. They're error prone (as you've found).
You need to add escaped quotes around the string parameter.
$('#result2').append("<button class ='removeBtn' onclick ='removeEbook(\'"+file+"\')'>Remove</button>");
you have to send file name in single quotes and use escape character for double qoutes like belwo
$('#result2').append("<button class =\"removeBtn\" onclick =\"removeEbook('"+file+"')\">Remove</button>");

Pass multiple values with onClick in HTML link

Hi Im trying to pass multiple values with the HTML onclick function. Im using Javascript to create the Table
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
But in my Javascript function the userName is undefined and the valuationId is a string with the valuationId and the UserName combined
function ReAssign(valautionId, userName) {
valautionId;
userName;
}
If valuationId and user are JavaScript variables, and the source code is plain static HTML, not generated by any means, you should try:
Re-Assign
If they are generated from PHP, and they contain string values, use the escaped quoting around each variables like this:
<?php
echo 'Re-Assign';
?>
The logic is similar to the updated code in the question, which generates code using JavaScript (maybe using jQuery?): don't forget to apply the escaped quotes to each variable:
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
The moral of the story is
'someString(\''+'otherString'+','+'yetAnotherString'+'\')'
Will get evaluated as:
someString('otherString,yetAnotherString');
Whereas you would need:
someString('otherString','yetAnotherString');
Solution: Pass multiple arguments with onclick for html generated in JS
For html generated in JS , do as below (we are using single quote as
string wrapper).
Each argument has to wrapped in a single quote else
all of yours argument will be considered as a single argument like
functionName('a,b') , now its a single argument with value a,b.
We have to use string escape character backslash() to close first argument
with single quote, give a separator comma in between and then start next argument with a
single quote. (This is the magic code to use '\',\'')
Example:
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
$Name= "'".$row['Name']."'";
$Val1= "'".$row['Val1']."'";
$Year= "'".$row['Year']."'";
$Month="'".$row['Month']."'";
echo '<button type="button" onclick="fun('.$Id.','.$Val1.','.$Year.','.$Month.','.$Id.');" >submit</button>';
enclose each argument with backticks( ` )
example:
<button onclick="updateById(`id`, `name`)">update</button>
function updateById(id, name) {
alert(id + name );
...
}
Please try this
for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"
That is because you pass string to the function. Just remove quotes and pass real values:
Re-Assign
Guess the ReAssign function should return true or false.
A few things here...
If you want to call a function when the onclick event happens, you'll just want the function name plus the parameters.
Then if your parameters are a variable (which they look like they are), then you won't want quotes around them. Not only that, but if these are global variables, you'll want to add in "window." before that, because that's the object that holds all global variables.
Lastly, if these parameters aren't variables, you'll want to exclude the slashes to escape those characters. Since the value of onclick is wrapped by double quotes, single quotes won't be an issue. So your answer will look like this...
Re-Assign
There are a few extra things to note here, if you want more than a quick solution.
You looked like you were trying to use the + operator to combine strings in HTML. HTML is a scripting language, so when you're writing it, the whole thing is just a string itself. You can just skip these from now on, because it's not code your browser will be running (just a whole bunch of stuff, and anything that already exists is what has special meaning by the browser).
Next, you're using an anchor tag/link that doesn't actually take the user to another website, just runs some code. I'd use something else other than an anchor tag, with the appropriate CSS to format it to look the way you want. It really depends on the setting, but in many cases, a span tag will do. Give it a class (like class="runjs") and have a rule of CSS for that. To get it to imitate a link's behavior, use this:
.runjs {
cursor: pointer;
text-decoration: underline;
color: blue;
}
This lets you leave out the href attribute which you weren't using anyways.
Last, you probably want to use JavaScript to set the value of this link's onclick attribute instead of hand writing it. It keeps your page cleaner by keeping the code of your page separate from what the structure of your page. In your class, you could change all these links like this...
var links = document.getElementsByClassName('runjs');
for(var i = 0; i < links.length; i++)
links[i].onclick = function() { ReAssign('valuationId', window.user); };
While this won't work in some older browsers (because of the getElementsByClassName method), it's just three lines and does exactly what you're looking for. Each of these links has an anonymous function tied to them meaning they don't have any variable tied to them except that tag's onclick value. Plus if you wanted to, you could include more lines of code this way, all grouped up in one tidy location.
function ReAssign(valautionId, userName) {
var valautionId
var userName
alert(valautionId);
alert(userName);
}
Re-Assign

Categories

Resources