Get form action with button named action - javascript

Background
Using VanillaJS to obtain an HTML form's action attribute value.
Code
Here is the code and the fiddle:
<html>
<head>
<script type='text/javascript'>
function init() {
alert( document.forms['form-load'].action );
}
</script>
</head>
<body onload="init();">
<form name="form-load" id="form-load" action="http://google.com/q">
<input name="query" id="query" type="text" />
<button id="button-load" type="submit" name="action" value="load">Load</button>
</form>
</body>
</html>
Problem
The dialog shows [object HTMLButtonElement] where http://google.com/q was expected (using Firefox 32).
Question
How can the form's action attribute value be retrieved?
Update
The following question might be relevant:
Retrieve form's "name" attribute in Javascript whereas an input exists with name "name"

It's a bad idea to give form elements names that conflict with standard form property or method names. For example, avoid giving elements the following names: submit, method, action, reset.
If you must, get the attribute value using the .getAttribute() method instead:
function init() {
alert( document.forms['form-load'].getAttribute("action") );
}

I think it's a bad practice to name an attribute name with "name". Why not use id instead?
function init() {
alert( "By ID:" document.getElementById('form-load').getAttribute('action') );
}

Related

Page Load jQuery Form Submit does not work

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
submitForm($("#login-user-one"));
});
function submitForm(form) {
console.log($(form).attr("method"));
$(form).submit();
};
</script>
</head>
<body>
<form id="login-user-one" name="login" method="POST" action="/test.html">
<input name="userid" tabindex="1" value="MyUser">
<input name="pass" type="password" tabindex="2" value="MyPass">
<input type="submit" name="submit" value="1" tabindex="3">
</form>
</body>
</html>
I can't figure out why the above does not works. The log shows me the value of POST and yet it won't submit. There are no errors in the console.
JS Fiddle: https://jsfiddle.net/t48hk9qx/
Well, this is a new one for me.
Because your form has a named element with name="submit", that element reference is replacing the HTMLFormElement.prototype.submit() function.
From the documentation...
Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's action HTML attribute).
jQuery attempts to execute that function when programmaticaly submitting the form with something like
if (typeof element.submit === 'function') {
element.submit()
}
But in your case, element.submit is an HTMLInputElement.
Quick and easy solution, rename your submit element, or as is more commonly seen with single-button forms, just remove the name attribute.
If you must keep the submit button named "submit", this seems to work
function submitForm(form) {
// note, "form" is already a jQuery object
console.log(form.attr("method"));
HTMLFormElement.prototype.submit.call(form[0])
}
Remove name = submit in your input will resolve problem. https://codesandbox.io/s/64kl2l3wvk. I think because form.submit function is replaced by the the input with name = submit.

Autocomplete does not detect changes to the source object

I'm using jQuery's autocomplete() method on a text field with Object.getOwnPropertyNames(projects) as the source:
$(function() {
$("#project").autocomplete({source: Object.getOwnPropertyNames(projects)});
}
The Object.getOwnPropertyNames(projects) method returns an array of the projects object's property names.
This works just fine. However:
If the user enters a new value in the field (ie, a value that is not already a property of the projects object), then the value gets added as a property when a button is clicked (the page is not reloaded). Button click also resets the field. When I try entering a value in the field now, the suggestions list doesn't show the newly added property (unless I call the autocomplete method again). How do I resolve this?
Psst. If I assign the value of Object.getOwnPropertyNames(projects) to an array, use the array as the source in the autocomplete method and update the array on button click, then the suggestions list shows the newly added value.
The following function handles the button click:
$("#clock").click(function() {
if (!($("#project").val() in projects)) { //If value is not already a property
projects[$("#project").val()] = $("#skill").val(); //skill is another field
}
$('#theForm')[0].reset(); //theForm is the id of the form that contains the fields
}
Try updating the source option of the autocomplete after the localArr is updated:
$("#project").autocomplete("option", "source", localArr);
After the form is submitted, your page refreshes, so the javascript code runs again, and what your javascript code says is to auto-complete the input field with the elements from the given source. You have to make sure your source now includes the new project the user just added.
PHP example:
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script type="text/javascript">
var projects;
jQuery(function() {
projects = {project1: 1, project2: 2, project3: 3, project4: 4};
<?php if (isset($_GET['project'])): ?>
projects['<?php echo $_GET['project']?>'] = 'foobar';
<?php endif ?>
jQuery("[name=project]").autocomplete({source: Object.getOwnPropertyNames(projects)});
});
</script>
</head>
<body>
<form action="">
Project: <input type="text" name="project" value="<?php echo isset($_GET['project']) ? $_GET['project'] : ""?>"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
As #mimarcel pointed out, $("#project").autocomplete({source: Object.getOwnPropertyNames(projects)}); only created an array that wouldn't change when I updated the projects object. In order for the suggestions list to reflect changes on the object, I had to use a callback, like so:
$('#project').autocomplete({
source: function(request, response){
response(Object.getOwnPropertyNames(projects));
}
});

Strange issue with jQuery.get()

I'm having a strange behaviour with this code:
<script type="text/javascript">
function get()
{
alert("gggg");
jQuery.get (
"http://localhost:8080/c/portal/json_service",
{
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : document.getElementById("nombre")
}
);
}
</script>
<div>
<form>
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="button" value="Submit" onClick="javascript:get()"/>
</form>
</div>
Liferay portal gets blocked when the button "Submit" is pressed. The pop-up with the message "gggg" is showed, but after click ok on it, the page becomes blocked.
If I remove the line 'param : document.getElementById("nombre")', it doesn't block.
Can anyone explain me where is the error, or the reason of this behaviour?
Thanks in advance,
Rafa
The problem is that you're trying to pass an entire DOM element as the value for param, which jQuery isn't going to like. What type of element has ID nombre, and what property from that element do you want? If it's some kind of input, you likely want the value property, so you'd do:
param : document.getElementById("nombre").value
Updated Answer:
Thinking this through a little more, you should probably do this in a different way altogether. You're sending the data when the user clicks on the submit button, but remember if a user hits enter while typing in the input text box the form will submit but your code will not catch that.
A more robust solution would be to do it this way instead:
<div>
<form id="nombre_search">
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="submit" value="Submit"/>
</form>
</div>​
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#nombre_search").submit(function(){
$.get("http://localhost:8080/c/portal/json_service", {
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : $("#nombre").val()
});
return false;
});
});
</script>
Changes to your code:
Added an id to the form.
Made the submit button a submit button instead of just a button.
Placed code inside $(document).ready block.
Code runs when form is submitted not when button is clicked.
Hope this helps,
Sandro

Unable to `submit()` an html form after intercepting the submit with javascript

I'm trying to intercept the submission of a form in order to change the value of my keywords label.
I have the following code:
<HTML>
<FORM name="searchForm" method="get" action="tmp.html" >
<input type="text" name="keywords" />
<input type="button" name="submit" value="submit" onclick="formIntercept();"/>
</FORM>
<SCRIPT language="JavaScript">
document.searchForm.keywords.focus();
function formIntercept( ) {
var f = document.forms['searchForm'];
f.keywords.value = 'boo';
f.submit();
};
</SCRIPT>
</HTML>
When I run this in chrome and click the submit button the keywords label changes to boo, but the javascript console says:
Uncaught TypeError: Property 'submit' of object <#an HtmlFormElement> is not a function.
How can I submit the form with the manipulated keywords?
The reason for the error when trying to call form.submit() is that your submit button is called "submit". This means that the "submit" property of your Form object is now a reference to the submit button, overriding the "submit" method of the form's prototype.
Renaming the submit button would allow you to call the submit() method without error.
The problem is that when some element is <input type="submit" name="submit" /> submit() method will not work. The best solution to this situation is to change the name of that submit type input to something else for example button-submit etc.
<html>
<head></head>
<body>
<form name="searchForm" method="get" action="tmp.html" onsubmit="formIntercept(this);">
<input type="text" name="keywords" />
<input type="submit" name="submit" value="submit"/>
</form>
<script type="text/javascript">
document.searchForm.keywords.focus();
function formIntercept( form ) {
form.keywords.value = 'boo';
//form.submit();
}
</script>
</body>
</html>
See jQuery .submit().
$("form").submit( function() {
// TODO tweak your form data before it gets sent
});
Just change the name of submit button and it'll work!
Chris Butler explained the issue well.
You can use a native submit method of HTMLFormElement to work around a problem.
In your case:
function formIntercept( ) {
var f = document.forms['searchForm'];
f.keywords.value = 'boo';
HTMLFormElement.prototype.submit.call(f);
};

How to get the new value of an HTML input after a keypress has modified it?

I have an HTML input box
<input type="text" id="foo" value="bar">
I've attached a handler for the 'keyup' event, but if I retrieve the current value of the input box during the event handler, I get the value as it was, and not as it will be!
I've tried picking up 'keypress' and 'change' events, same problem.
I'm sure this is simple to solve, but at present I think the only solution is for me to use a short timeout to trigger some code a few milliseconds in the future!
Is there anyway to obtain the current value during those events?
EDIT: looks like I had a caching problem with my js file as I checked the same code later on and it worked just fine. I would delete the question, but not sure if that loses rep for the kind folk who posted ideas :)
Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with:
function showMe(e) {
// i am spammy!
alert(e.value);
}
....
<input type="text" id="foo" value="bar" onkeyup="showMe(this)" />
To give a modern approach to this question. This works well, including Ctrl+v. GlobalEventHandlers.oninput.
var onChange = function(evt) {
console.info(this.value);
// or
console.info(evt.target.value);
};
var input = document.getElementById('some-id');
input.addEventListener('input', onChange, false);
There are two kinds of input value: field's property and field's html attribute.
If you use keyup event and field.value you shuld get current value of the field.
It's not the case when you use field.getAttribute('value') which would return what's in the html attribute (value=""). The property represents what's been typed into the field and changes as you type, while attribute doesn't change automatically (you can change it using field.setAttribute method).
<html>
<head>
<script>
function callme(field) {
alert("field:" + field.value);
}
</script>
</head>
<body>
<form name="f1">
<input type="text" onkeyup="callme(this);" name="text1">
</form>
</body>
</html>
It looks like you can use the onkeyup to get the new value of the HTML input control. Hope it helps.
Here is a table of the different events and the levels of browser support. You need to pick an event which is supported across at least all modern browsers.
As you will see from the table, the keypress and change event do not have uniform support whereas the keyup event does.
Also make sure you attach the event handler using a cross-browser-compatible method...
You can try this code (requires jQuery):
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#foo').keyup(function(e) {
var v = $('#foo').val();
$('#debug').val(v);
})
});
</script>
</head>
<body>
<form>
<input type="text" id="foo" value="bar"><br>
<textarea id="debug"></textarea>
</form>
</body>
</html>

Categories

Resources