jQuery - How to aply custom CSS to fields which are not empty - javascript

I have some fields with class="required" which has custom css.
When i submit the form, i see an custom error message which aplies the required fields the css:
$(".required").addClass('required-fields');
Now, when i complete some fields (not all required) and i submit again de form, maybe what i need to see is: in the fields which have data (not empty), should go another css. Like border green or something like that.
Is it possible to do with a for maybe?

You could try something like this:
$('.required').removeClass('ok').filter(function(){
return !!$(this).val();
}).addClass('ok');
It filters all required fields with a value and adds class 'ok';
http://jsfiddle.net/cHPS2/

You can check if the input has a value. For example if($("#nameInput).value) will be true if its not blank. You can add a class to those inputs.
for(var i=0;i<inputs.length;i++){
if(inputs[i].value){
//enter add class code here
}
}

You have to pass on every input with a Jquery selector like
var $fields = $('.field');
And check if the field is required or not and if a value is given or not like :
$fields.each(function ($field) {
if ($field.hasClass('required') && !$field.value) {
$field.addClass('required-fields');
}
else {
$field.addClass('green-fields');
}
});
It's a rapid draft :)

Form validation with user feedback is a sufficiently common requirement that you may wish to consider using a plugin rather than coding a custom solution (reinventing the wheel) each time:
http://jqueryvalidation.org/documentation

You may try something like following (Can't be more pecific because you didn't provide HTML):
$('.required').not('[value=""]').css(...);
Using css() you may change the look of your elements.
Update:
To add a class to them try this:
$('.required').not('[value=""]').addClass('className');
To remove a class and then add another class (Also you may use toggleClass) try this:
$('.required').not('[value=""]').removeClass('className').addClass('className');
An Example.

Try this:
$('input.required:text').filter(function() {
return $(this).val() == "";
}).css(...);

Related

Change attribute

I've got a selection/dropdown with ID #pa_buy-sell[]. What I want to do is if the value is "buy" I want to change the attribute data-required="yes" to data-required="no" from a input field with class wpuf__regular_price_657. I also want to hide the span with class required. The code has to work in WordPress.
I'm quite new in this, so I'm not sure what's the right code. But I thought something like this could be a good starting point:
$('#pa_buy-sell[]').change(function(){
if($(this).val() == 'buy'){
//something need to happen here
}
});
Can someone help me with this?
Your code is correct until now. You have to replace the comment with the following lines:
$('.wpuf__regular_price_657').data('required','no');
$('span.required').hide();
To change the attribute to yes or no. you can use this:
$(".wpuf__regular_price_657").attr("data-required","no");
or you can use disabled as true or false, if you dont want to take input as
$(".wpuf__regular_price_657").attr("disabled", true);
and for hiding the particular span:
$("span.required").hide();
This will work fine in wordpress too
Hope it helped you
Please check with "===" which confirms Strong type checking (type and value) comparison and also refer the code for hiding the div with class required.
<script>
var $ = jQuery.noConflict();
$('.pa_buy-sell.wpuf_pa_buy-sell_657').change(function(){
if($(this).val() === "buy"){
$(".wpuf__regular_price_657").attr("data-required","no");
$("span.required").hide();
}
});
</script>

How to bind change event dynamically in jquery

I am doing username availability check. I made jquery ajax call, its working fine and if username already in use i want to make label and textbox in red color. for this purpose i am adding css class in the callback function of $Post() method. The problem I have is css is not applying. I think the problem is in dynamically binding the event So please can any one help me in this. Here is my jquery script,
$(document).on('change', '#uName', function() {
var uName = $(this).val();//get the string typed by user
if (uName!=''){
$.post('<%=request.getContextPath()%>/controller/UserNameCheckController',{'uName':uName},
function(data) {
$('.status').html(data);
var status = $.trim($("#status").text());
if(status=="Username in use try another"){
$('#unameBlock').addClass('error');
}
});
}
else{
$('.status').html('');
}
});
Help me to fix this please. Thanks.
I think the error lies on your class selector
Change
$.trim($("#status").text());
to
$.trim($(".status").text());
//--------^-----------------
try changing it to
var status = $.trim($("#status").html());
it could be .status or #status depends upon the class or id you have used in your html.

How do I validate a tinyMCE editor, if it is blank by appending a string next to it?

I need to validate a form. This form has some dropdowns and tinyMCE editor, I am validating this form by appending the string "Required" after each field if it is blank, However I am unable to validate the tinyMCE editor, if the editor is blank, I tried something like
tinyMCE.get('tinyedotor').getContent();
but no luck.
here is my fiddle
getContent() should work just fine. Your fiddle doesn't contain the form validation code for the editor value, which is quite crucial here. Try this:
var editorContent = tinyMCE.get('tinyeditor').getContent();
if (editorContent == '')
{
// Editor empty
}
else
{
// Editor contains a value
}
Forked fiddle
Also note you've declared multiple id's for your select drop-down.
Edit: You can get the id of the editor container with the getContainer() method: tinyMCE.get('tinyeditor').getContainer(). Inserting an error message after the editor would then be something like this:
$('<span class="error">Editor empty</span>').insertAfter($(tinyMCE.get('tinyeditor').getContainer()));
This, however, will create a new span each time the user clicks the submit button, so you'll probably want to have an error message container with a unique id and check if the container already exists before inserting it.
Edit 2: Updated fiddle.
You can do this to check if the content is empty without parsing html:
var content = tinymce.get('tinymceEditor').getContent({format: 'text'});
if($.trim(content) == '')
{
// editor is empty ...
}
What you want can be easily done. Her is a link to a fiddle with my solution.
Using the getcontent() is the proper way, but what if user enters the space !!??Here is the complete solution with the RegEX -
var content = tinyMCE.get('tinyeditor').getContent(), patt;
//Here goes the RegEx
patt = /^<p>( \s)+( )+<\/p>$/g;
if (content == '' || patt.test(content)) {
$('.bgcolor').css("border", "1px solid Red")
return false;
} else {
$('.bgcolor').removeAttr("style");
return true;
}
Note: ('.bgcolor') is nothing but a div around the 'tinyeditor' to have the red border when validation occurs.
Late to the party but with tinyMCE V4
Following worked for me.
tinymce.init({
selector: '#editorHtml'
});
function IsCreatePostValid() {
tinyMCE.triggerSave();
if ($('#editorHtml').val().trim().length <= 0) {
return false;
}
return true;
}
where #editorHtml is a text area, and on triggerSave MCE is populating the current rich text editor value to respective textarea.
so I am checking the textarea.
getContent() is the way to go. You could just use the tinyMCE.activeEditor object and call getContent() on that or get the editor instance by id, like you're doing.
It looks like you've got a typo in your id, which is probably causing your issue.
tinyMCE.get('tinyedotor').getContent();
should probably be:
tinyMCE.get('tinyeditor').getContent();

Change the class of a input field

Sorry. Let me rephrase:
I want js to change to class of a input field if it is left empty; Here is my code to detect a empty field:
function validateForm()
{
var ctrl = document.forms["form1"]["username"];
var x=ctrl.value;
if (x==null || x=="") {
////////////CHANGE INPUT CLASS/////////////
}
else {
document.getElementById('username').style.backgroundColor="#FFFFFF";
}
}
i would have to css classes:
.inputfield {
background-color:white;
}
.inputfieldempty {
background-color:red;
}
To prevent submitting you need to call a function for the onsubmit event of the form (e.g. onsubmit="return checkFields()". In the function you will do the validations and return true or false depending on that. If the function will return false then the form will not be posted.
As part of your validations when you determine that a field's value is empty you can do the desired css changes as well. I don't know if you use vanilla javascript or a library such as jQuery in order to give more specific details.
Have a look at this tutorial for the excellent jQuery Validation plugin, which does exactly what you need and you don't even have to fiddle with cross-browser concerns.
If you don't want to use the plugin, I still recommend at least to use jQuery. Here's another tutorial that goes through all the necessary steps.
This post should take care of adding your CSS classes: Change an element's class with JavaScript
This post should take care of preventing forms to submit: https://developer.mozilla.org/en/DOM/event.preventDefault

How to enable/disable text field on radio button interaction?

Cannot get this to work. First time using variables passed into functions. Unchecking radio button should disable form field and vice versa. lineid variable distinguishes this radio/text input pair from 10 others.
My code:
<script type="text/javascript">
function disablefield(lineid){
if (document.getElementById(lineid).checked == true){
document.dupedit.lineid.disabled = false;
} else {
document.dupedit.lineid.disabled = true;
}
}
</script>
Subset of my HTML.
You need to pass a string into your disablefield function, so put the value in quotes when you pass it in. Something like:
<input onclick="disablefield('2671997')" />
This is because document.getElementById expects a string, not an integer.
Secondly, to enable/disable the field, you need to use disabled = true; rather than = 'disabled'.
document.dupedit.lineid is looking a for a field with name "lineid", which doesn't exist in your form. I would suggest giving the field an id and using document.getElementById again instead.
If you want to continue using the name attribute, you will have to use document.getElementsByName instead. This returns an array of matching elements (since multiple elements can share the same name), but if in your code you know that the element in question is the only one with that name, you can do this:
document.getElementsByName(lineid)[0].disabled = true;
You can see a working version (I think this is how you wanted it anyway) here. And here is a version using getElementsByName.
You are missing a closing brace on the function:
function disablefield(lineid){
if (document.getElementById(lineid).checked == true){
document.dupedit.lineid='enabled';
}else{
document.dupedit.lineid='disabled';
}
} //<-- here
Also, can I suggest you pass this to the function. Then you don't have to call getElementById
<input onclick='disablefield(this)' type.....
function disablefield(obj){
if (obj.checked == true){
document.dupedit.lineid='enabled';
}else{
document.dupedit.lineid='disabled';
}
}
I think what you need is to re-think the code.
Don't use ID on the checkbox. Better move that ID to the text field you want to disable/enable and check whether that field is disabled/enabled, not the checkbox itself
use cleaner JS.
Please, take a look at the jsFiddle, I have compiled for you. Does it do what you expect, Dan?

Categories

Resources