I trying to validate a form using ajax...I have got it to show either a cross or tick if the box passes valdation. This is done by showing or hiding a div tag, is there an easier way without me having to have a div tag for each cross & tick as this would use about 20 div tags.
Thanks
You could use the CSS :before property to do this:
.tick:before {
content:url(tick.gif);
}
.cross:before {
content:url(cross.gif);
}
(you'll probably have to tweak the CSS a bit to get the image to display in the proper position)
Then in your javascript, just add the class tick or cross to each text box that you want to display an image next to.
Since your validation depends on javascript you could leave the divs out of the html initially and insert them after validating a field. Let's say your source is something like:
<p><input id="email" name="email" type="text" value="" /></p>
Your script could be something like:
var emailField = document.getElementById('email');
if( isValid(emailField) ){
var tick = document.createElement('DIV');
tick.className = 'tick';
emailField.parentNode.appendChild(tick);
}else{
var cross= document.createElement('DIV');
cross.className = 'cross';
emailField.parentNode.appendChild(cross);
}
You add the classes '.tick' and '.cross' to your css and apply background images. Of course, you need some checking if the element was already inserted by a previous validation. This is just a simple example.
This way you don't need the extra divs initially.
Related
I'm creating an address form for my web application and am having trouble figuring out the styling rules for HTML5 form validation with the required attribute. The examples and behavior described below are using Firefox.
The HTML for the first input field of the form looks like this:
<label for="addressLine1" class="form__label">
Address Line 1
</label>
<input type="text" required aria-required="true" class="form__input-text" id="addressLine1"/>
Without any custom styling the input behaves like this:
When the page loads, the input field displays the default styling for a text input
If I try to submit the form with the required input blank, the browser adds a red border (or shadow?) to the input
I want to retain this behavior, where the input displays some default styling on load, and only displays "invalid" styling if the user tries to submit the form with any required fields blank (or otherwise invalid). But I can't find a straight answer as to what attributes/pseudo classes I need to modify to change the styling while retaining this behavior. If I use the :invalid pseudo class, I get this behavior:
On load, the input already has my "invalid" styling, because the field is blank
If I try to submit the form with the field blank, the browser adds the red border/shadow on top of my "invalid" styling
I can only get my default/valid styling to appear by entering valid data into the input
How do you retain the default behavior (default styling on load, invalid styling on invalid submission) with custom styles, and can it be done with just CSS or do I have to add some JS functionality?
Alright so after reading over the CSS Pseudo Class docs on MDN, it doesn't look like there is any combination of pseudo classes you can string together to model the various states that make this behavior work correctly. So after playing around a bit and looking over the Bootstrap validation link Alex Schaeffer suggested, but deciding I didn't want to add extra dependencies/style sheets I didn't really need, here's the solution I came up with that adds minimal extra CSS and JavaScript.
First off, the red border was, indeed, a box shadow, so I was able to override that just by adding this to my (S)CSS:
.form__input-text {
/* default input styling goes here */
box-shadow: none;
}
Next, I added a bit of state to my component to keep track of whether or not the form has been validated yet. I'm using Svelte, so this was as simple as adding a boolean variable inside the component's <script> tag like so:
let wasValidated = false;
Then I added a conditional class to my HTML/JSX. If you're using another framework or jQuery/vanilla JS, you might need to explicitly do this with a function wired to an event handler, but in Svelte I just need to change my markup to this:
<label for="addressLine1" class="form__label">
Address Line 1
</label>
<input
type="text"
required aria-required="true"
class="form__input-text"
class:wasValidated="{wasValidated}"
id="addressLine1"
/>
All the class:wasValidated="{wasValidated}" bit is doing is conditionally adding a .wasValidated class to that input element if/when the wasValidated variable is truthy.
Then, back in my (S)CSS I added the following to apply my "invalid" styling (which at this point just changes to border color to a shade of red) only when the form had been validated at least once, and only to invalid elements:
input.wasValidated:invalid {
border-color: $red;
}
Then I wired a simple onClick function to the submit button that changes the wasValidated variable to true when the button is clicked:
HTML/JSX
<button on:click|preventDefault={onClick} class="form__submit-button" type="submit">
Search
</button>
JS
const onClick = e => {
wasValidated = true;
};
The function needs to be wired to a click event and not a submit event, because the submit event is never triggered if the form fails validation.
So now, when the page first loads, all the form inputs display the default styling, regardless of validity, because wasValidated is set to false. Then, when the submit button is clicked wasValidated is toggled to true, the .wasValidated class is applied to any required elements, which, if they are invalid, then display the "invalid" styling. Otherwise, if the form is successfully submitted, the onSubmit function wired to the form handles things from there.
Edit: As it turns out, in Svelte, you can unbind event handlers after the first time the event fires. So my markup for the submit button now looks like this:
<button on:click|preventDefault|once={onClick} class="form__submit-button" type="submit">
Search
</button>
Adding the |once modifier to on:click unbinds the onClick function the first time the button is clicked, so the function doesn't keep firing unnecessarily if the user attempts to submit invalid data multiple times.
How do you retain the default behavior (default styling on load,
invalid styling on invalid submission) with custom styles, and can it
be done with just CSS or do I have to add some JS functionality?
You can achieve this effect with a very small amount of javascript (four lines).
The reason why your input is showing as invalid is because it is both empty and required.
So one 3-step approach looks like this:
Step 1: Declare the element in your HTML using the attribute required
<input type="text" required>
Step 2: Then remove that attribute via javascript immediately
const addressLine1Input = document.getElementById('addressLine1');
addressLine1Input.removeAttribute('required');
Step 3: Then, as soon as a single character is entered into the <input> use javascript a second time to add the required attribute back in again.
const setRequired = (e) => e.target.required = 'required';
addressLine1Input.addEventListener('keyup', setRequired, false);
You can test that all this is working below by adding one or several characters to the <input> and then deleting all of them.
You will see that the <input> is initially empty but does not show as invalid, then contains characters and does not show as invalid and, finally, is empty again and now does show as invalid.
Working Example:
const addressLine1Input = document.getElementById('addressLine1');
addressLine1Input.removeAttribute('required');
const setRequired = (e) => e.target.required = 'required';
addressLine1Input.addEventListener('keyup', setRequired, false);
input:invalid {
background-color: rgba(255, 0, 0, 0.3);
border: 2px solid rgba(255, 0, 0, 0.5);
}
<form>
<label for="addressLine1" class="form__label">Address Line 1</label>
<input type="text" name="addressLine1" id="addressLine1" class="form__input-text" placeholder="Enter address here..." aria-required="true" required>
</form>
I don't think that this is possible with pure CSS, you also need some JavaScript
CSS
#addressLine1{
border: none;
background: none;
outline: none;
border-bottom: 1px solid black;
}
JS
document.getElementById('form_id').addEventListener('submit',function(e){
let address = document.getElementById('addressLine1').value
if(address == ""){
e.preventDefault()
address.style.borderBottomColor = "red";
}else{
address.style.borderBottomColor = "black";
}
})
The easiest way to accomplish unified styling across all browsers would be to use Bootstrap Validation https://getbootstrap.com/docs/4.0/components/forms/?#validation.
How do I make a textarea and input type="text" highlightable and copyable on iOS-devices?
This does not work:
<textarea readonly="readonly">Totally readonly, cannot be copied</textarea>
Neither does:
<textarea disabled="disabled">Totally readonly, cannot be copied</textarea>
EDIT: The text-area is constantly being updated, so a one-off transformation of it won't work.
The content of the textarea can also be HTML.
I have a JSFiddle that I tested this on: http://jsfiddle.net/sebnilsson/jfvWZ/
One solution could be to find all the readonly textareas on the page and render a div with the contents in place of the read only field. I have written some very simple JS to demonstrate this.
Something along the lines of
$('textarea[readonly]').removeAttr('readonly').each(function () {
var $this = $(this);
$this.hide().after('<div data-textarea="' + $this.attr('id')
+ '" class="textarea">' + $this.val() + '</div>');
}).on('textareachange', function () {
var $this = $(this);
$('[data-textarea="' + $this.attr('id') + '"]').html($this.val());
});
You will also need to trigger the event when you update the textarea value.
For example
$('textarea').val('test').trigger('textareachange');
There's a more extensive example here with examples on the styling etc.
http://jsfiddle.net/ssfUx/3/
I've successfull select some text on my iPhone, but needs many try.
<textarea readonly onfocus="this.blur();">Totally readonly, CAN BE copied</textarea>
and the last : http://jsfiddle.net/jfvWZ/6/
<div>
<label>Plain div</label><br />
<div id="plain-div" onFocus="this.blur();">
Plain div
</div>
</div>
Easy to select the text on iPhone
Likewise ran into this issue.
Not sure if the following is a decent, correct or semantic alternative, but it worked for me.
I simply changed the textarea to a div readonly, same styles applied.
The one drawback is that in JavaScript I couldn't target the div with this['myForm']. It doesn't appear to be a child of the form element in DOM.
Instead I had to get the element by id and set it's innerHTML, rather than set the value as with textarea.
It worked on Ipad 1 IOS5 and Iphone 4s IOS7 I am now able to select and copy text to clipboard.
I have a recaptcha widget in my form and i want it to be made mandatory.
since i dont have any direct control over the widget in my html, i was wondering if i can add the required attribute to it after it has been rendered.
ie. if i add the folloing css
#recaptcha_response_field{background-color:#000000;}
it does color up the recaptcha widget text field. in the same vein, if there was some way of setting the required="required" attribute for input fields via css, i'd be able to make it mandatory.
Does the following work for you:
$(function() {
$("#recaptcha_response_field").attr('required','required');
});
If I understand you correctly, this should do the trick:
$(function() {
$("#recaptcha_response_field").css({background-color:#000000;});
});
Without jQuery:
document.onload = function() {
document.getElementById("recaptcha_response_field").style['background-color'] = '#000000';
};
I'm not 100% sure on the second one, but I can't test it right now.
I have a form input tag with some text assigned to its value attribute:
<input type="text" name="firstName" value="First Name*" />
Since this is a required field, how do I style the asterisk at the end of the "First Name*" string to be the color red? Is this even possible?... How do you style the values of pre-populated form fields?
Thank you.
I think you're making this more complicated then it should. There may be a way using javascript or jquery but I think that's overkill.
I would just put it on the outside of the box and style it within a <span> tag.
I don't think you can style one character to be red but you could style the whole string to be red.
What I would probably do is set the asterisk outside the input box and style it like this
<input ...value="FirstName"><span style="color: #FF0000;">*</span>
No, it's impossible. You'd have to fake it.
However, that's what <label>s are for!!
<label>First Name* <input name=firstName required></label>
Even if it would be possible, it'd not be a good practice. Data should always be separated from the representation. You don't want anything else but the data that you really need to be posted.
It'd be a good idea to go with the jQuery solution that simply assigns a class to the input field on post if there's an error, e.g. makes the text inside the input red, draws the red border around the input box etc.
If you're using asp .net why not just use the required field validator control and let it do the work for you.
Instead of adding * to the field, I would suggest signifying the required field by modifying the element's styling through CSS and jQuery/JavaScript.
Working example: http://jsfiddle.net/wstGQ/
CSS:
input {
color: #ccc;
}
.required {
color: #FF0000;
border: 1px solid #FF0000;
}
jQuery:
$('input').focus(function(){
var obj= $(this);
var oldVal = obj.val();
obj.blur(function(){
if(obj.val() == oldVal){
obj.val('Please enter a valid option').addClass('required');
}else{
obj.removeClass('required');
}
});
});
Is there a way to put text in a textbox but also allow the user to type something. I would like to write "username:" inside the box and allow the user to type after the colon. I can do this the hard way by creating a div right next to a textbox and make it look like they are one container, but I was wondering if there was an easier way? Thanks
EDIT: I don't want to text to disappear. I just want to user to be able to continue typing
EDIT 2: the reason you cant put a value in the textbox is because its a form. when the user types a username next to the value it will submit together
HTML5 has a placeholder attribute you can now use:
<input type="text" placeholder="username" />
People have also created javascript functions that mimic this functionality.
There's also a jQuery placeholder plugin which does the same, if you'd like to go that route.
What's wrong with using standard HTML? You don't say that you need it to disappear...
<input type="text" value="username: " />
If you need it to disappear, use a placeholder attribute and a jQuery plugin as a fallback (for the browsers that don't support it.
You could do something like this:
<div>
<label>Username:</label>
<input type="text" />
</div>
CSS
div{border:1px solid gray;}
label{font-family:arial; font-size:.8em;}
input{border:none;}
input:focus{outline:none;}
Basically, created a containing div and placed a label and input in that div. label is the words that stay in the field. input has the border removed.
http://jsfiddle.net/jasongennaro/rZmFx/
Fyi... you may need to increase the size of the input, depending on how many characters you want to accept.
<input type="text" placeholder="Category"/>
Maybe that can help you. If you want the textbox for only read you can put the property readonly = "".
You could call this javascript function once the page is loaded:
function add(text){
var TheTextBox = document.getElementById("Mytextbox");
TheTextBox.value = TheTextBox.value + text;
}
If you are using HTML5, you can use the placeholder attribute.
http://www.w3schools.com/html5/att_input_placeholder.asp