I have an input text and an empty label in html
<div class="form-group">
<label for="hsDetailsForm-name">Denumire</label>
<input id="hsDetailsForm-name" type="text" class="form-control" ng-model="hydroStation.name" placeholder="Obligatoriu" required ng-blur="validationObliga()" autofocus/>
<label id="obliga"></label>
</div>
and here is the function in js
$scope.validationObliga = function () {
var value = $.trim($("hsDetailsForm-name").val());
if (value == "") {
$('#obliga').html("Campul este obligatoriuu!").css("color", "red");
} else {
$('#obliga').html("");
}
}
ng-blur works and when empty it writes "Campul este obligatoriuu!" in red, however when you type something in the text field and focus out of it, it still says that, it doesnt change the label to "". Why don't it go in the else ?
The error here is you've missed # of the id selector.
Although, adding # in the selector will solve your problem, I won't recommend you to use jQuery here, use AngularJS as follow
Controller:
$scope.validationObliga = function () {
var value = $scope.hydroStation.name.trim();
$scope.showMessage = value === "";
};
View:
<div class="form-group">
<label for="hsDetailsForm-name">Denumire</label>
<input type="text" class="form-control" ng-model="hydroStation.name" placeholder="Obligatoriu" required ng-blur="validationObliga()" autofocus/>
<label ng-show="showMessage" class="error">Campul este obligatoriuu!</label>
<!-- ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^ Add this --->
</div>
CSS:
.error {
color: red;
}
You missed the anchor here; should be...
var value = $.trim($("#hsDetailsForm-name").val());
... so that you look for an element with id equal to hsDetailsForm-name. As it stands, you look for an element hsDetailsForm-name - and there's none. As result, jQuery element is empty, its val() is undefined, and $.trim(undefined) results in an empty string.
Related
Hi I have a small problem.
I have an input bar which sometimes need to be shown in a form and sometimes not.
I am afraid that if someone put data and then hide it and press send, the data will be sent. So I want to reset the input each time it is hidden.
ng-change isn't a good idea because it doesn't let my write anything.
<div class="form-group" ng-show="isItOne=='1' || isItTwo=='2'">
<label class="col-md-1">someName</label>
<div class="col-md-4">
<input class="form-control" type="text" name="someOtherName" ng-model="nameModel" ng-change="clearWhenChanged()">
</div>
</div>
and this is the function
$scope.clearWhenChanged = function() {
$scope.nameModel = "";
};
take out the show condition and use it to control visibility and model value.
$scope.showHideField = function(){
if(isItOne=='1' || isItTwo=='2'){
return true;
}
$scope.nameModel= "";
}
call it in your div:
<div class="form-group" ng-show="showHideField()">
this also provides the flexibility to pass a flag based on which you can decide whether to clear the field's value or not .. :)
You could call a function instead where you set the isItOne variable. In that function you could set the variable to 1 or 2 and clear the model value.
HTML
<div class="form-group" ng-show="show()">
<label class="col-md-1">someName</label>
<div class="col-md-4">
<input class="form-control" type="text" name="someOtherName" ng-model="nameModel" ng-change="clearWhenChanged()">
</div>
</div>
Controller
$scope.show = function() {
if ($scope.isItOne == '1' || $scope.isItOne == '2');
return true;
$scope.nameModel = '';
}
Having said all that it might be a better option to just simply unset the model's value on submit in cases when you don't want it to be sent.
use the tag attribute ng-if="your condition", This will render the tag only when the condition is true. Otherwise it will remove the whole input from DOM.
Have this problem that form inputs with assigned mask (as a placeholder) are not validated as empty by jQuery validation.
I use:
https://github.com/RobinHerbots/jquery.inputmask
https://github.com/1000hz/bootstrap-validator
(which uses jQuery native validation in this case)
Some strange behaviors:
Inputs with attribute required are validated (by jQuery) as not empty and therefore valid, but in the other hand input is not considered as "not empty" and not checked for other validation rules (this is by validator.js)
When i write something into input field and then erase it, I get required error message
Can anyone give me some hint?
EDIT:
Relevant code:
HTML/PHP:
<form enctype="multipart/form-data" method="post" id="feedback">
<div class="kontakt-form-row form-group">
<div class="kontakt-form">
<label for="phone" class="element">
phone<span class="required">*</span>
</label>
</div>
<div class="kontakt-form">
<div class="element">
<input id="phone" name="phone" ' . (isset($user['phone']) ? 'value="' . $user['phone'] . '"' : '') . ' type="text" maxlength="20" class="form-control" required="required" data-remote="/validator.php">
</div>
</div>
<div class="help-block with-errors"></div>
</div>
</form>
JS:
$(document).ready(function() {
$('#phone').inputmask("+48 999 999 999");
$('#feedback').validator();
});
I managed to use the RobinHerbots's Inputmask (3.3.11), with jQuery Validate, by activating clearIncomplete. See Input mask documentation dedicated section:
Clear the incomplete input on blur
$(document).ready(function(){
$("#date").inputmask("99/99/9999",{ "clearIncomplete": true });
});
Personnaly, when possible, I prefer setting this by HTML data attribute:
data-inputmask-clearincomplete="true"
The drawback is: partial input is erased when focus is lost, but I can live with that. So maybe you too ...
Edit: if you need to add the mask validation to the rest of your jQuery Validate process, you can simulate a jQuery Validate error by doing the following:
// Get jQuery Validate validator currently attached
var validator = $form.data('validator');
// Get inputs violating masks
var $maskedInputList
= $(':input[data-inputmask-mask]:not([data-inputmask-mask=""])');
var $incompleteMaskedInputList
= $maskedInputList.filter(function() {
return !$(this).inputmask("isComplete");
});
if ($incompleteMaskedInputList.length > 0)
{
var errors = {};
$incompleteMaskedInputList.each(function () {
var $input = $(this);
var inputName = $input.prop('name');
errors[inputName]
= localize('IncompleteMaskedInput_Message');
});
// Display each mask violation error as jQuery Validate error
validator.showErrors(errors);
// Cancel submit if any such error
isAllInputmaskValid = false;
}
// jQuery Validate validation
var isAllInputValid = validator.form();
// Cancel submit if any of the two validation process fails
if (!isAllInputValid ||
!isAllInputmaskValid) {
return;
}
// Form submit
$form.submit();
It's not exactly the solution, but...
changing inputmask for some equivalent solves the problem.
Still far from perfect, though : (
EXPLANATION:
Other masking libraries, don't have these two strange behaviors mentioned, so it's possible to validate fields.
I used:
https://github.com/digitalBush/jquery.maskedinput
I have the same issue when combined these two libs together.
Actually there is a similar ticket here: https://github.com/RobinHerbots/Inputmask/issues/1034
Here is the solution provided by RobinHerbots:
$("#inputPhone").inputmask("999.999.9999", {showMaskOnFocus: false, showMaskOnHover: false});
The validator assumes that it is not empty when the mask focus/hover is there.
simply turn focus and hover of the mask off will fix the problem.
I solved this problem with:
phone_number: {
presence: {message: '^ Prosimy o podanie numeru telefonu'},
format: {
pattern: '(\\(?(\\+|00)?48\\)?)?[ -]?\\d{3}[ -]?\\d{3}[ -]?\\d{3}',
message: function (value, attribute, validatorOptions, attributes, globalOptions) {
return validate.format("^ Nieprawidłowa wartość w polu Telefon");
}
},
length: {
minimum: 15,
message: '^ Prosimy o podanie numeru telefonu'
},
},
I am attempting to preview my name and step element in my form, so the user can see if they have made a mistake. I am able to preview the step however the name just won't work. Can anyone see why?
http://jsfiddle.net/pocockn/rw54b/
$(document).ready(function() {
var commentNode = $('#lp-step'),
nameNode = $('#lp-name'),
name = $('#name');
$('#live-preview-form input, #live-preview-form textarea').bind('blur keyup',function() {
commentNode.text($('#step_1').val());
commentNode.html($('#lp-step').html().replace(/\n/g,'<br />'));
if($('#name').val()) {
nameNode.text(name.val() + ' says:');
}
else {
return false;
}
});
});
You can't have two elements with the same ID, if you do it will only select the first element it finds. (in this case its the div which is always empty and never runs your if statement). You have your div with id=name and your input. So I changed your div id to nameDiv instead.
Id's should be unique to avoid confusion.
<div id="nameDiv">
<label for="name">Enter recipe name:</label>
<input type="text" id="name" name="name">
<br />
</div>
http://jsfiddle.net/trevordowdle/rw54b/1/
my requirement is to save the entire "html" inside a div, but when i load an "html" with text fields to a div and then editing the value of the text box, the newly set value doesn't reflect in the core "html". I tried to inspect the value with fire bug and it remains the same or no value at all.With "jquery" i tried to set attribute but no attribute name value is created. how can i set the value of text fields and then get that "html" with the newly set value.
here is my html
<div class="sub_input_box">
<input type="text" / class="boreder_line">
<input type="text" id="txt" value=""/>
<input type="hidden" id="hid" />
<div class="clear"></div>
</div>
and the jquery i used to set attribute
$("#txt").attr("value", "some value");
Chances are you're calling your jQuery code before the HTML input part. You can either place the jQuery stuff below it, or if you don't want to, you can do something like this:
$(document).ready(function(){
$("#txt").attr("value", "some value");
});
That will only run when the page is fully loaded.
However, it's unclear if you're using AJAX to load those inputs into your DOM. If so, you need to call $("#txt").attr("value", "some value"); in the onSuccess callback function which is fired after the AJAX successfully responds.
You can try something like this:-
<input name="example" type="text" id="example"
size="50" value="MyDefaultText" onfocus="if(this.value=='MyDefaultText')this.value=''"
onblur="if(this.value=='')this.value='MyDefaultText'" />
Have you tried:
$("#txt").val("Hello World!");
For setting the text value, and,
var my_string = $("#txt").val();
For getting the text value.
Let me know if it works.
Excellent question. You would think clone would do this on its own, alas, it doesn't.
Here is a sample than you can hopefully adapt to do what you need
HTML
<div id=divToCopy>
<input name=i1 value=foo><br>
<input name=i2 value=bar>
</div>
<input type=button onclick=copyDiv(); value='Copy the div'>
<div id=newDiv>
the copy will go here
</div>
JavaScript
function copyDiv() {
$('#newDiv').html($('#divToCopy').clone());
$('#divToCopy :input').each(function() {
var child=0;
for (var i = 0; i < this.attributes.length; i++) {
var attrib = this.attributes[i];
var prop=$(this).prop(attrib.name);
$($('#newDiv').find(' :input')[child]).prop(attrib.name,prop);
child++;
}
});
}
But it does work: http://jsbin.com/eXEROtU/1/edit
var html = '<input type="text" id="txt" value=""/>';
$(document).ready(function() {
$("#load").click(function() {
$("#sub_input_box").html(html);
});
$("#inspect").click(function() {
alert($("#txt").val());
});
});
$(document).on('focusout','input[type="text"]',function(a){
console.log(a.target.value);
a.target.setAttribute("value",a.target.value);
});
this is the solution i found, i had to set the value attribute explicitly on loose focus from the text field
I have an HTML with say a textfield (input element).
<input name="capacity" type="text" value="blah blah blah">
This simply displays a text field on my page with a default value "blah blah blah".
What I want to do is remove value attribute, as I don't want to see this default value.
I am doing this using javascript.
value = element.getAttribute("value");
if((element.readOnly != undefined || element.readOnly == false) || (element.disabled != undefined || element.disabled == false)){
//element.removeAttribute(value);
element.removeAttribute("value");
But it is not working. I even tried
element.setAttribute("value","");
but no luck.
Any pointers where I may be missing.
EDIT :
I got an issue related to this question, anyone interested may check this
*********************************************
Thanks a lot.
...I don't want to see this default value.
Just set the value property directly to an empty string.
document.getElementsByName('capacity')[0].value = '';
jsFiddle.
Give your text field and id like <input name="capacity" type="text" id="text" value="blah blah blah"> document.getElementById['text'].value = "";
This is your html tag. You will need to add a ID to it
<input id="capacity" name="capacity" type="text" value="blah blah blah">
This is just to fire the javascript function
<input type="submit" value="Click" onclick="javascript:return reset();" />
The following function will reset the value of the selected element
<script type="text/javascript" language="javascript">
function reset() {
document.getElementById("capacity").value = "";
return false; // In order to avoid postback
}
</script>
If you are not using form and you want to use it with just the name you can try the following
this.capacity.value = '';