IE 6 and the multiple button elements all sending their name & values - javascript

When using multiple button elements in a form, I realised that IE7 sends the innerHTML instead of the value of the button. All good I thought, I'll simply change my PHP code to this
<?php
if (isset($_POST['button-name'])) {
add_product_to_cart(2);
}
?>
Now my old friend IE6 is going a little step further at being a nuisance. It sends all of the button elements regardless of which one I click. For example, I have 3 button elements named 'mint', 'near-mint' & 'standard'. A quick print_r($_POST) tells me that all 3 names have been submitted.
I guess to remedy this will be some JavaScript, not the most elegant situation, but I can imagine that the average user still using IE6 is not bright enough to turn off their JavaScript.
How can I remedy this?

I found a solution at http://www.codecomments.com/JavaScript/message756646.html
All credit to the author on that page.
Per request, here is the code
function buttonfix(){
var buttons = document.getElementsByTagName('button');
for (var i=0; i<buttons.length; i++) {
buttons[i].onclick = function () {
for(j=0; j<this.form.elements.length; j++)
if( this.form.elements[j].tagName == 'BUTTON' )
this.form.elements[j].disabled = true;
this.disabled=false;
}
}
}
window.attachEvent("onload", buttonfix);

This is a known bug in Internet Explorer.
http://www.dev-archive.net/articles/forms/multiple-submit-buttons.html describes a workaround that does not depend on JavaScript.
It boils down to "Use <input> and don't design your buttons to need anything other than simple text for their labels".

An solution is to use <input type="button"> and <input type="submit"> in your page instead of <button type="button"> and <button>.
Update: if you change your button elements to input elements you should be able to find them using jQuery with the following selector:
var buttons = $('input[type=submit], input[type=button]');

Related

Give an input button with no value HTML tag a different value

I'm using UserWP plugin in Wordpress and on my registration page I have the form and the button which says "Submit Query" - not the best text. I'd much rather have "Register".
There's no option in the settings to change the button text so trying to utilise another method.
The HTML string for the button is:
<input type="submit" name="uwp_register_submit" class="form-control btn btn-primary btn-block text-uppercase uwp_register_submit">
So there is no "value" for the text.
My aim is to "inject" the value="Register" into the HTML string. I believe this can be done with a JavaScript snippet, but not being the best at JS, I'm struggling to achieve it.
Lots of googling found some JS code that finds a text string in the identifier and replaces it, however I cannot seem to get this working.
const button = document.querySelector('input');
button.addEventListener('click', updateButton);
function updateButton() {
if (button.value === '') {
button.value = 'Register';
}
}
I realise this would only take effect on click, so when the button is pressed. So tried something like:
const button = document.querySelector('input');
if (button.value === '') {
button.value = 'Register';
}
Again, no success.
And I also saw something about using jquery? So tried the following without success.
$('.btn').val('Register');
I simply want to target the class of the button and tell it to give a value of "Register" - I bet it's an easy solution for someone, but not me...
In general you can achieve that by getting the element and setting the value as you try.
But the line document.querySelector('input'); gives you back the first matching element back. See MDN Document.querySelector
So if there are more than one input fields, it will take the first input, which may not be your submit input.
An alternative would be to search for the specific name of the input field.
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector("[name='uwp_register_submit']").value = "Register";
});
If that field exists multiple times, use querySelectorAll and combine it with an loop.
In your specific case it would maybe the better way to change the default translation for english. Have a look at the documentation. It looks more complicated as it is.

Why select retain the value previously selected after reload [duplicate]

I have a big problem with the functionality in Firefox that keeps data that the user have filled in on reload F5. If i use Ctrl+F5 the forms are cleared and this is great. My problem is that not all my users know that this is what they have to do to force the input cleanup. Is there a way in the html or response headers to tell Firefox to not keep the data in the forms?
Just add autocomplete="off" to your inputs and you will solve the problem.
<input type="text" autocomplete="off">
jQuery to solve this on all inputs and textareas
$('input,textarea').attr('autocomplete', 'off');
Instead of going through all inputs you may also just add the attribute to your form-element like so:
<form method="post" autocomplete="off">...</form>
However the above mentioned methods on domReady did not work for me...
In case you want to keep the autocomplete feature of the browser (see other valid answers), try adding the name attribute to the form and give it a random value. It has worked for me:
<form id="my-form" name="<random-hash>">
...
</form>
/*reset form elements (firefox saves it)*/
function resetElements()
{
var inputs = document.querySelectorAll('input[type=text]');
//you get the idea.....you can retrieve all inputs by tag name input
for(var i = 0; i < inputs.length; i++) {
document.getElementsByTagName('input')[i].value = "";
}
var textareas = document.getElementsByTagName('textarea');
for(var i = 0; i < textareas.length; i++) {
document.getElementsByTagName('textarea')[i].value = "";
}
}
Call this function onload.
I think easier and quicker way to do that is
$('input,textarea').attr('autocomplete', 'off');
I tried the shortened solution above, but it didn't clear the value of the select boxes on my page.
I ended up modifying it slightly and now all input types on the page are cleared regardless of type:
var allInputs = $(":input");
$(allInputs).attr('autocomplete', 'off');
So to make this run onload I just put it in the ready() method:
$(document).ready(function () {
var allInputs = $(":input");
$(allInputs).attr('autocomplete', 'off');
});
I found the only fix for me was to do
document.forms[0].reset();
before doc ready early in the page, as suggested in the comment by #Marek above - not great but worked for me (the autocomplete attribute method via either jQuery, JS or HTML didn't in the end fix it for me)
just to piggyback on #jonnybradley's solution (couldn't comment on his answer because I don't have enough rep yet):
This also worked perfectly form me:
document.getElementById('theFormId').reset();
called after the HTML code.
one of my colleagues recommended that we should use a random string as the name of the form. It works very well if you don't use the name attribute of the form.
it is an example from the sf1 form builder:
public function renderFormTag($url, array $attributes = [])
{
..
$attributes['name'] = isset($attributes['name']) ? $attributes['name'] : bin2hex(random_bytes(16));
..
}
autocomplete="off" is also needed for hidden input fields in order to have them refreshed on simple page reload (F5)

Mandatory Free-Form-Text Fields

I have radio buttons for a online form. Following the [URL="https://netsuite.custhelp.com/app/answers/detail/a_id/14704/"]NS help page for radio buttons[/URL], I made my fields free-form-text. I went to the Online Form record (Setup -> Marketing -> Online Customer Forms) and tried to make the radio button fields mandatory. While it keeps the "Yes" for Mandatory, it doesn't seem to apply it when I process the form.
Is there something I have to do to make Free-form-text fields mandatory?
I dont think radio buttons can be made mandatory since they only hold a Yes/No value. If you do not select anything, it will default to No. This is the same case with checkboxes.
For mandatory fields, I think the system looks for null or empty values.
NetSuite's Mandatory appears to look at the Value attribute in a form element (radio button), it may be getting the value of the first radio button in a group, even if none are checked, and see there is something there. Because of this, I solved this issue with an HTML5 element and Javascript. I am answering my own question to help others with this:
HTML5 Approach:
The easy way is in HTML5 input fields have a new attribute called "required". Just add this to the end of the input tag and it will make the field required. Any HTML5 compliant browser will handle this. Example is:
<input value="Very Satisfied" name="custrecord208" type="radio" id="custrecord208" class="radio1" required>Very Satisfied
Javascript Approach:
Unfortunately, not all users use the latest browsers (HTML5 compliant) much to developers' dismay. Below is the code I wrote in Javascript for this particular problem. It may not be the cleanest but it got the job done.
function saveRecord_validation(){
//array of the id's you know you need to go through
var a_custRecNames = ['custrecord184', 'custrecord185', 'custrecord186', 'custrecord187', 'custrecord188'];
var s_quesNums="";
var isFormValid = true;
var isRadioChecked = false;
for( var i = 0; i < a_custRecNames.length; i++ ) {//loop through each mandatory customRecord
var radios = document.getElementsByName(a_custRecNames[i]); //get the radio buttons for that question
//reset isRadioChecked for each question
isRadioChecked = false;
for (var j = 0, length = radios.length; j < length; j++) {//loop through each radio button
if (radios[j].checked) {
// only one radio can be logically checked, don't check the rest
isRadioChecked = true;
break;
}
}
if(!isRadioChecked){
//cleaning up the output just a little.
s_quesNums = ((i+1) < a_custRecNames.length) ? s_quesNums.concat(i+1).concat(", ") : s_quesNums.concat(i+1)+".";
isFormValid = false;
}
}
if(!isFormValid){
alert( "Please answer question(s) "+s_quesNums);
return false;
}
return true;
}
Add this to the Online Form in NetSuite (for help visit NetSuite Answers: Attach Script to Form).
For help with creating Radio Buttons in NetSuite to begin with, visit NetSuite Answers: Use Radio Button values on Online HTML forms

How to pass a user entered form value from html to javascript?

It is possible to pass a value from javascript to html by writing it to a tag. However, if I would wish to pass a user defined value (etc, entered by the person viewing the webpage) to java script so I can do things with it, what would be the most easiest way possible?
At the moment, I have something like this:
<div class="entry foreground-color">
<form>
<input type="text" name="commands" size="60"/>
</form>
</div>
How can I make the value from the form be passed to my javascript?
Or, am I going in a totally wrong direction? If so, what would be the correct way to get user input, and pass it on to javascript?
EDIT: Apologies for my misuse of terminology. I am making a text based adventure game, and I want the user to be able to type in a response, press enter, and have the response be sent to javascript, so I can use javascript to evaluate the response (etc "go south", "go north"), and write back to the element with the new situation (etc "as you went south, you found a troll").
You can just stop the form from submitting and get the value:
HTML:
<div class="entry foreground-color">
<form onsubmit="return getValue('commands')">
<input type="text" name="commands" size="60" id="commands"/>
</form>
</div>
JavaScript:
function getValue (id) {
text = document.getElementById(id).value; //value of the text input
alert(text);
return false;
}
Fiddle: Fiddle
If you want to clear the box afterwards, use:
document.getElementById(id).value = '';
Like so:
function getValue (id) {
text = document.getElementById(id).value; //value of the text input
alert(text);
document.getElementById(id).value = '';
return false;
}
The input value is already available for Javascript via DOM API:
document.getElementsByName( "commands" )[0].value
You can get the value of your input control using:
document.getElementsByName("commands")[0].value;
Since getElementsByName() method returns an Array of elements with specified name, you will need to take the first element assuming that there is only one elements with name attribute commands.
Instead of that, for simplicity and uniqueness, i suggest you use the famous way to achieve that using id attribute and getElementById() method.
<input type="text" name="commands" size="60" id="commands"/>
var input = document.getElementById("commands").value;
or
document.getElementsByName( "commands" )[0].value
now do anything with this
To get the value of an HTML element, first, you need to get the desired element (you can use theses methods):
getElementById
getElementsByTagName
getElementsByClassName
querySelector (moderns browsers)
querySelectorAll (moderns browsers)
Theses methods depending on document (documentation).
So in your case you can try something like this:
var inputs = document.getElementsByTagName('input'),
commandValue = null;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name === "commands") {
commandValue = inputs[i].value; // get the element value
}
}
alert (commandValue); // show the value
But you need to set a "catcher" on the form default action.
So:
<form>
Become:
<form onsubmit="return getValue()">
And you set the javascript code above in the getValue function:
function getValue() {
var inputs = document.getElementsByTagName('input'),
commandValue = null;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name === "commands") {
commandValue = inputs[i].value; // get the element value
}
}
alert (commandValue); // show the value
return false; // prevent default form action
};
You are in the right path :)
For example you can do something like this (see http://jsfiddle.net/ahLch/):
HTML:
<h1 id="commandsExample"></h1>
<div class="entry foreground-color">
<form>
<input type="text" id="commands" size="60"/>
</form>
</div>
JavaScript:
var input = document.getElementById('commands');
var example = document.getElementById('commandsExample');
input.addEventListener('change', function () {
example.innerHTML= input.value;
});
A couple of things to note:
If you are new to JavaScript, and you wish to make your code cross browser (especially if you want to target old versions of IE), take a look to jQuery.
If you wish to learn how to use plain DOM APIs provided by the browser without the jQuery layer, take a look to: http://youmightnotneedjquery.com/ (it's very useful once that you learned jQuery basics).
There are a couple of ways to get the value:
Intercepting from submmit event: I don't recommend it, you have to take care of avoiding the default submit behavior, and you have to create a form around your input field. That was necessary in old browsers, but today is not.
change event: it's fired when the input value has changed and the input looses the focus (is the usual event used for form validation).
keydown and keyup: they give you more control, by capturing each keystroke, but it's lower level than the change event. For a complete reference see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
Use "id" instead of "name". Name is only necessary when you want to submit the value, in new browsers you can leave just input tag without a form.
Getting the value of the input tag is quite easy with jQuery.
(I take it you need this anyway to actually send the message via AJAX to a server..?)
$("#idofinput").val(); will copy the value, $("#idofinput").val(''); will empty it.
You probably want to do this without actually submitting a form.
Recreating one in javascript isn't to hard.
For the submit on enter you can use something like this:
function checkEnter(e)
{
var keynum;
if(window.event) // IE8 and earlier
{
keynum = e.keyCode;
}
else if(e.which) // IE9/Firefox/Chrome/Opera/Safari
{
keynum = e.which;
}
if(keynum==13)
{
sendMessage();
}
}

Disable Applet button using javascript

I would like to disable a button
<BUTTON name="Next Page" onClick="Next()" VALUE="NextPage">NextPage</button>
based on a javascript variable
var opening = 0;
function Next()
{
var currentdoc = viewONE.getDocIndex();
if (currentdoc == 5)
{
**[DISABLE BUTTON]**
}
what is the javascript code please?
Background information:
Simply browsing through documents using a next and previous buttons. on the first document i want the "previous" button greyed out and on the the last document i want the "next" button greyed out.
Appologise for any incorect terms, newb and never asked this type of question before.
you are welcome to correct my term in a constructive way... need to learn.
Sam's solution is good and will disable the action of the button but won't disable it functionally.
You can disable the input button by changing changing the "disabled" attribute, but you really need to give your button a valid identifier first (I wouldn't even want to let jQuery select it by name due to the space).
jQuery would look something like this:
$('#yourbuttonid').attr('disabled','disabled');
Regular Javascript would be the following:
document.getElementById('yourbuttonid').disabled = true;
Here's an example on JSBin.
All you need to do is:
var opening = 0;
function Next()
{
var currentdoc = viewONE.getDocIndex();
if (currentdoc == 5)
{
return; //This will end the function immediately.
}
}
In terms of greying out buttons, can you not add / remove classes to show different versions of the buttons? We would need more to see your html, and what you have tried so far to help further.
Tutorial on return

Categories