Conditional Formatting in Html? - html

I am writing a website and I am currently working on the sign up page. I have a drop down box and I want to have that drop down box open different sign up information for each one. For example: If they picked prime user it would change the sign up information they needed from just username and password to username, password, credit card number, and telephone number . OR if they picked partial user from the drop down list it would ask for username password and telephone. Any clue how to do this in HTML or any other computer language?

Assuming html like this:
Type:<br>
one <input type="radio" name="type" id="type-1" value="1" /><br>
two <input type="radio" name="type" id="type-2" value="2" />
<hr>
<form action="." METHOD="POST">
<input class="second" type="text" name="name" id="name" value="name" />
<input class="second" type="text" name="email" id="email" value="email" />
<input class="second" type="text" name="credit-card" id="credit-card" value="credit card" />
</form>
And css like this: (to hide all the form fields except for type choice)
.second{
display:none
}
You can use jQuery javascript library to show/hide the required form fields dynamically like this:
// when type radio button is pressed
$('#type-1,#type-2').change(function(){
// hide all form fields
$('.second').hide()
// if type is 1
if($('#type-1:checked').length){
// show name and email fields
$('#name,#email').show()
// else if type is 2
}else if($('#type-2:checked').length){
// show name, email and credit-card fields
$('#name,#email,#credit-card').show()
}
})
This is demonstrated here: http://jsfiddle.net/rBvLA/
The result must be processed by server side script using any language you choose.

You might want to look into any of the many fine server side tools available, such as asp.net, php, etc... you could also use javascript.
For instance, using JavaScript, you could have an event fire when they change the drop down and in the code for that event handler, you could modify the DOM in such a way as to display the appropriate form elements for each selection.

another jQuery solution:
Live Demo
$('#reg_type input[type=radio]').change(function() {
var type = $(this).attr('class');
$('#reg_fields div').each(function() {
if ($(this).hasClass(type)) {
$(this).show().removeAttr('disabled');
} else {
$(this).hide().attr('disabled','disabled');
}
});
});

Related

How to have 2 textboxes as mutually exclusive in an html form?

I would like to have 2 mutually exclusive fields.
One will be a FileField and other TextBoxField.
Is there a ready html form I can get my hands on to.
I have searched the web and couldnt find any.
Oh I am a little sorry..
I meant that I wanted to do this via Django Templates
You can make an onInput event listener and handle it using javascript, so that if the user types in one field it empties the other.
For example:
<form>
<label for="first">Fill This:</label>
<input type="text" name="first" id="first" oninput="run('first')"><br><br>
<label for="second">Or This:</label>
<input type="text" name="second" id="second" oninput="run('second')"><br><br>
<input type="submit" value="Submit">
</form>
<script>
function run(activeField) {
if (activeField == 'first') {
const second = document.querySelector('#second')
second.value = ''
} else {
const first = document.querySelector('#first')
first.value = ''
}
}
</script>
For Your textbox, you can use this:
<input type="text" name="name" placeholder="Please enter your name">
And for your files:
<input type="file" name="fileName">
But for file name it needs to be encrypted. HTML won't let you submit a form with a file. But you can override this in the form attr, like this:
<form action="dirToForm.py" method="POST" enctype="multipart/form-data"></form>

Multiple values in radio input within form with vanilla HTML

I am aiming to create a form to handle disabled JavaScript experience for a small component on my website. Currently I have the following form:
<form method="GET" action="https://mywebsite.com/somedirectory/">
<input type="radio" id="uid1" name="someParam" value="fruity" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" value="veggie" />
<label for="uid2">Vegetable</label>
...other radio options
<input type="submit" value="Submit" />
</form>
Clicking on either of the radio options and then on the submit button will result in:
option 1: https://mywebsite.com/somedirectory/?someParam=fruity
option 2: https://mywebsite.com/somedirectory/?someParam=veggie
How can I add another value for each of the radio options? Say I would like to pass someOtherParam which is unique for each option and I would like to get this as output for my options:
option 1: https://mywebsite.com/somedirectory/?someParam=fruity&someOtherParam=apple
option 2: https://mywebsite.com/somedirectory/?someParam=veggie&someOtherParam=pepper
What I have tried is:
<input type="radio" id="uid1" name="someParam" value="fruity&someOtherParam=apple" />
<input type="radio" id="uid2" name="someParam" value="veggie&someOtherParam=pepper" />
However, the & symbol is converted to %26 inside the link and feels too hacky. Is there a better way to achieve this? Also, is there a way to make sure the Submit button is only enabled once a radio option is selected?
P.S. I am aiming for pure HTML experience with no Javascript involved. Is that possible?
I'm pretty sure this is not posible in modern browsers without the use of JS. Maybe on old browsers you could do some tricks with CSS and display:none because it used to not send fields with display:none, but nowdays that is not an option.
If you can allow Javascript, you can add a data attribute to each radio option and use it to populate an extra hidden input on change.
document.querySelectorAll('input[type=radio][name="someParam"]')
.forEach(radio => radio.addEventListener('change', (event) =>
document.getElementById('someOtherParam').value = event.target.dataset.extraValue
));
<form method="GET" action="https://mywebsite.com/somedirectory/">
<input type="radio" id="uid1" name="someParam" value="fruity" data-extra-value="apple" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" value="veggie" data-extra-value="pepper" />
<label for="uid2">Vegetable</label>
<input type="hidden" id="someOtherParam" name="someOtherParam">
<input type="submit" value="Submit" />
</form>
To add another radio group independent from others, use a distinct name property. For example, to add a second parameter called someOtherParam to the request, create a radio group with name="someOtherParam":
<input type="radio" id="uid3" name="someOtherParam" value="apple" />
<input type="radio" id="uid4" name="someOtherParam" value="pepper" />
And add their correspondent labels.
Also, is there a way to make sure the Submit button is only enabled once a radio option is selected?
You can add the required attribute to prevent the browser to send the form before all the inputs have a value.
Without javascript, what you're describing cannot be done.
What you could do, as other posters have suggested is:
Create radio buttons for the list of options that are possible for each category (fruits / vegetables etc)
<input type="radio" id="uid3" name="someOtherParam" value="apple" />
<input type="radio" id="uid4" name="someOtherParam" value="pepper" />
When processing the input on your server side code, check if you have received a value or not. If not, you can choose a default option (apple or whatever). On your page you can mention what the default option would be in case they don't make a selection.
You could make some of the input required as suggested, but you would still have to make check on the server side that the input has been received, since the required attribute is just a suggestion to users browsers - it won't stop a malicious persons from making a request without that parameter by running a script etc.
To submit extra information to the server, you can use a hidden input type and change value as per your needs using javascript.
HTML code
<form method="GET" action="">
<input type="radio" id="uid1" name="someParam" value="fruity" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" value="veggie" />
<label for="uid2">Vegetable</label>
<input type="hidden" id="uid3" name="someOtherParam" value="" readonly required />
<input type="submit" value="Submit" onclick="onSubmit()" />
</form>
Javascript code
function onSubmit () {
let fruityRadio = document.getElementById( 'uid1' );
let veggieRadio = document.getElementById( 'uid2' );
if ( fruityRadio.checked ) {
document.getElementById( 'uid3' ).value = 'apple';
} else if ( veggieRadio.checked ) {
document.getElementById( 'uid3' ).value = 'pepper';
}
}
Easy, double up the value with a deliminator between every extra value:
HTML
<div>
<label for="uid1">
<input id="uid1" name="fruit1" type="radio" value="apple:orange" />
Fruit, Apple + Orange
</label>
</div>
<div>
<label for="uid2">
<input id="uid2" name="fruit1" type="radio" value="apple:cherry:lime" />
Fruit, Apple + Cherry + Lime
</label>
</div>
node.js
I'm not sure how node.js handles what PHP refers simply as $_POST['name_attribute_value_here'] though I do know you simply want to use .split(':') to get the two or more values from that single form. If you want more options per radio button just append a deliminator (it doesn't have to be :) between each value.
Both of those radio options have the name "fruit1" so the user can't choose both.
No JavaScript is necessary.
A minor adaptation on the server.
Extra values will obviously not appear to the server if the user doesn't select that radio form field.
Arrays
If you want to set your own key/values then just add a second deliminator:
<input name="fruit1" value="fruit:apple,fruit:lime,color:purple,planet:Earth" />
Then at the server use [whatever].split(',') to get the pairs and iterate in a loop to get each key/value. You could create an entire crazy multi-dimensional array if you really wanted to.
I hope this helps, feel free to comment if you need any further clarification.
Generate form:
const data = [
{ name: 'apple', type:"fruity" },
{ name: 'pepper', type:"veggie"}
]
const form = document.querySelector('form');
const uid = document.querySelector('#uid')
createOptions(data);
function createOptions(data){
data.forEach((e, index) => {
const f = document.createDocumentFragment();
const l = document.createElement('label');
const i = document.createElement('input');
l.setAttribute('for', `uid${index+1}`);
l.textContent=e.name;
i.setAttribute('type', `radio`);
i.setAttribute('for', `uid${index+1}`);
i.setAttribute('name', 'someOtherParam');
i.setAttribute('value', e.name);
i.dataset.otype = e.type;
f.appendChild(l);
f.appendChild(i);
form.insertBefore(f, uid);
i.addEventListener('change', onselectChange, false);
})
}
function onselectChange(event) {
uid.value = event.target.dataset.otype;
}
<form method="GET" action="https://mywebsite.com/somedirectory/">
<input type="text" id="uid" name="someParam"
style="width:0; visibility: hidden;">
<input type="submit" value="Submit" />
</form>
I can't think another way of doing this using less code, the following achieves your desired result:
<form name="form" method="GET" action="">
<input type="radio" id="uid1" name="someParam" required value="fruity" onchange="document.form.someOtherParam.value = 'apple'" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" required value="veggie" onchange="document.form.someOtherParam.value = 'pepper'" />
<label for="uid2">Vegetable</label>
<input type="hidden" name="someOtherParam" value=""/>
<input type="submit" value="Submit"/>
</form>
There's only 3 changes to your example:
Add a name to the form, then add inline attributes required and onchange to each radio, finally add an input[type=hidden] to include the extra param. The first change is meant so you'll not need document.getElementById later, the second so the form won't be empty submitted and also update the hidden desired value.

How can I change or remove HTML form validation default error messages?

For example I have a textfield. The field is mandatory, only numbers are required and length of value must be 10. When I try to submit form with value which length is 5, the default error message appears: Please match the requested format
<input type="text" required="" pattern="[0-9]{10}" value="">
How can I change HTML form validation errors default messages?
If the 1st point can be done, is there a way to create some property files and set in that files custom error messages?
This is the JavaScript solution:
<input type="text"
pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Please enter Alphabets.')"
onchange="try{setCustomValidity('')}catch(e){}" />
The "onchange" event needs when you set an invalid input data, then correct the input and send the form again.
I've tested it on Firefox, Chrome and Safari.
But for Modern Browsers:
Modern browsers didn't need any JavaScript for validation.
Just do it like this:
<input type="text"
pattern="[a-zA-Z]+"
title="Please enter Alphabets."
required="" />
When using pattern= it will display whatever you put in the title attrib, so no JS required just do:
<input type="text" required="" pattern="[0-9]{10}" value="" title="This is an error message" />
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Plz enter on Alphabets ')" />
I found this code in another post.
HTML:
<input type="text" pattern="[0-9]{10}" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" />
JAVASCRIPT :
function InvalidMsg(textbox) {
if(textbox.validity.patternMismatch){
textbox.setCustomValidity('please enter 10 numeric value.');
}
else {
textbox.setCustomValidity('');
}
return true;
}
Fiddle Demo
To prevent the browser validation message from appearing in your document, with jQuery:
$('input, select, textarea').on("invalid", function(e) {
e.preventDefault();
});
you can remove this alert by doing following:
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity(' ')"
/>
just set the custom message to one blank space
you can change them via constraint validation api: http://www.w3.org/TR/html5/constraints.html#dom-cva-setcustomvalidity
if you want an easy solution, you can rock out civem.js, Custom Input Validation Error Messages JavaScript lib
download here: https://github.com/javanto/civem.js
live demo here: http://jsfiddle.net/hleinone/njSbH/
The setCustomValidity let you change the default validation message.Here is a simple exmaple of how to use it.
var age = document.getElementById('age');
age.form.onsubmit = function () {
age.setCustomValidity("This is not a valid age.");
};
I Found a way Accidentally Now:
you can need use this: data-error:""
<input type="username" class="form-control" name="username" value=""
placeholder="the least 4 character"
data-minlength="4" data-minlength-error="the least 4 character"
data-error="This is a custom Errot Text fot patern and fill blank"
max-length="15" pattern="[A-Za-z0-9]{4,}"
title="4~15 character" required/>
I found a bug on Mahoor13 answer, it's not working in loop so I've fixed it with this correction:
HTML:
<input type="email" id="eid" name="email_field" oninput="check(this)">
Javascript:
function check(input) {
if(input.validity.typeMismatch){
input.setCustomValidity("Dude '" + input.value + "' is not a valid email. Enter something nice!!");
}
else {
input.setCustomValidity("");
}
}
It will perfectly running in loop.
This is work for me in Chrome
<input type="text" name="product_title" class="form-control"
required placeholder="Product Name" value="" pattern="([A-z0-9À-ž\s]){2,}"
oninvalid="setCustomValidity('Please enter on Producut Name at least 2 characters long')" />
To set custom error message for HTML validation use,
oninvalid="this.setCustomValidity('Your custom message goes here.')"
and to remove this message when user enters valid data use,
onkeyup="setCustomValidity('')"
As you can see here:
html5 oninvalid doesn't work after fixed the input field
Is good to you put in that way, for when you fix the error disapear the warning message.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')" />

How can I make an input field read only but still have it send data back to a form?

I have an input field:
<input cid="Topic_Created" name="Topic.Created" size="25" type="text" value="6/5/2011 8:22:45 AM" />
I want the field to display on my form but don't want the user to be able to edit the field. When the user clicks submit I want the form value to be sent back to the server.
Is this possible. I tried different combinations of disabled = "disabled", readonly = "readonly". Seems I always get nothing sent back for the field.
Adding a hidden field with the same name will sends the data when the form is submitted.
<input type="hidden" name="my_name" value="blablabla" />
<input type="text" name="my_name" value="blablabla" disabled="disabled" />
With Chrome browser on Windows 10 just having name="your_name" and the readonly attributes works fine: client cannot change a value, but it is sent to the server.
On the assumption you're using a script to create the form, I'd suggest using <input type="hidden" /> which will submit the variable with the form, but also use a regular <input type="text" readonly="readonly" /> to show the variable to the user. This won't submit the value, obviously, but will make it visible (while the hidden input will submit the value, but not show the value).
You could also do this with JavaScript:
var theForm = document.getElementsByTagName('form')[0];
var inputs = document.getElementsByTagName('input');
for (i=0; i<inputs.length; i++){
if(inputs[i].type == 'hidden'){
var newInput = document.createElement('input');
newInput.type = 'text';
newInput.setAttribute('disabled');
newInput.value = inputs[i].value;
theForm.appendChild(newInput);
}
}
Clumsy JS Fiddle demo.
alternatively u can make a little manipulation with javascript, remove the disabled property before form submitted
<form action="target.php" method="post">
<input type="text" id="anu" name="anu" value="data anu" disabled="disabled" />
<button onclick="document.getElementById('anu').disabled=''">send</button>
<script type="text/javascript">
function myFn(event) {
event.stopPropagation(); event.preventDefault();
}
</script>
<input onkeydown="myFn(event)" >
You can add 'readonly'='true' in the input element. With this the user cant edit and also send the value back to the server.
<input cid="Topic_Created" name="Topic.Created" size="25" type="text" value="6/5/2011 8:22:45 AM" readonly='true' />
You should consider using input type="hidden" when submitting read-only fields. Otherwise, if you still need the value of input field to be visible, you should create another input (type=text) with a different name.
<input cid="Topic_Created" name="Topic.Created" type="hidden" value="6/5/2011 8:22:45 AM" />
<!--This is visible: -->
<input cid="Topic_Created" name="doesntmatter" size="25" type="text" value="6/5/2011 8:22:45 AM" />

Adding Data To An Input Field

I'm trying to add a search box to my page that will direct users to the search result page on a different site. I have the action and all of the other required data in hidden fields, to ensure it's posting correctly.
The problem is that they tack on extra data to the search term, making it an advanced search type of field. So instead of being searchTerm=X, it's expecting searchTerm=Locale(en):FQE=(KE,None,11)MY_SEARCH_TERM:And:LQE=(AC,None,8)fulltext$
How can I add that extra data around my search term, without having to hit an intermediate page to do the concatenation?
Here's what I have so far:
<form action="http://vendors.address/searchresult.do" method="post">
<input type="hidden" name="type" value="search">
<input type="hidden" name="sort" value="DateDescend">
<input type="text" name="queryId">
</form>
And I need something that can result in this type of thing:
<form action="http://vendors.address/searchresult.do" method="post">
<input type="hidden" name="type" value="search">
<input type="hidden" name="sort" value="DateDescend">
<input type="hidden" name="queryId" value="Locale%28en%2C%2C%29%3AFQE%3D%28KE%2CNone%2C11%29MY_SEARCH_TERM_HERE%3AAnd%3ALQE%3D%28AC%2CNone%2C8%29fulltext%24">
</form>
Any help would be appreciated.
You could use Javascript to do this with a hidden search field. In jQuery, it would be something like:
$("input[name='queryId']").keyup(function() {
$("#hiddenField").val("Locale%28en%2C%2C%29%3AFQE%3D%28KE%2CNone%2C11%29" + $(this).val() + "%3AAnd%3ALQE%3D%28AC%2CNone%2C8%29fulltext%24");
});
But it would break with no JS.
Edit: Yea, beat to it, didn't refresh for the answers.
You can use JavaScript to do the concatenation before the form is submitted. There are a couple ways to do this but here is the recommended approach:
Since I don't see a submit button I'm assuming you counting your users to hit the enter key to submit the form so you will need to listen to the onSubmit event and concatenate the extra info before the post is sent to server.
Give the form element an id:
<form action="..." method="post" id="searchForm">
and give the text input field an id:
<input type="text" name="queryId" id="queryId">
Add this script block after the form
<script>
document.getElementById("searchForm").onSubmit = function(){
var queryField = document.getElementById("queryId");
queryField.value = "prepend_data" + queryField.value + "append_data";
return true;
}
</script>
Or of you can use JQuery (please do) you can drop this anywhere:
<script>
$(function(){
$("#searchForm")
.submit(
function(){
$("#queryId).val("prepend_data" + $(this).val() + "append_data");
}
);
});
</script>
Hope that helps
Two things I can think of:
1. Just put the locale and stuff in hidden inputs:
<input type="hidden" name="locale" value="en" />
2. Use javascript to submit the form (this is a horrible idea -- you don't want to make your site break if Javascript is turned off).