I have code that allows a user to pick between 2 options of a person TYPEA and TYPEB.
SELECT PERSON - { TYPEA, TYPEB }
Depending on the choice, it shows:
TYPEA - { TYPEA WITH ID, TYPEA WITHOUT ID }
TYPEB - { TYPEB WITH ID, TYPEB WITHOUT ID }
It is working with this:
html:
<div id="person-A-withID" class="persons" style="display:none"></div>
<div id="person-A-withoutID" class="persons" style="display:none"></div>
<div id="person-B-withID" class="persons" style="display:none"></div>
<div id="person-B-withoutID" class="persons" style="display:none"></div>
jQuery:
$(function () {
$('#has_id').show();
$('#select_person').change(function () {
$('.persons').hide();
if ($('#select_person').val() == 'typeA') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type A--').appendTo("#has_id");
$("<option/>").val('person-A-withID').text('person-A-withID').appendTo("#has_id");
$("<option/>").val('person-A-withoutID').text('person-A-withoutID').appendTo("#has_id");
}
if ($('#select_person').val() == 'typeB') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type B--').appendTo("#has_id");
$("<option/>").val('person-B-withID').text('person-B-withID').appendTo("#has_id");
$("<option/>").val('person-B-withoutID').text('person-B-withoutID').appendTo("#has_id");
}
});
$('#has_id').change(function () {
$('.persons').hide();
$('#' + $(this).val()).show();
});
});
I have a function to validate if the value is empty or equals 0 with the following code:
function validate(id, msg) {
//search object
var obj = $('#' + id);
if(obj.val() == '0' || obj.val() == ''){
//append error to particular div called #id__field_box
$("#" + id + "_field_box .form-error").html(msg)
return true;
}
return false;
}
and I call it inside a validate function like this:
var validation = function(){
var err = 0;
err += validate('select_person', "select person.");
//err += validate($('#select_person:first-child').attr('has_id'), "Select wether it has ID or not.");
//err += validate('has_id', "Select wether it has ID or not.");
if(err == 0){
//continue
}else{
//stop
}
};
Now, the problem is that I cannot validate the has_id part, I am only able to validate the first one. How can I use it to search for has_id?
here is a fiddle, please take a look at it
In your example, there isn't an element with the id of 'selector_persona'. This prevents your second validate function from working. By passing it the id of what you're trying to validate ('has_id'), it references the object and checks to make sure it has a value.
Choose a person, leave the second select as "--Choose Type A--" and click ok. It returns your error.
http://jsfiddle.net/zyglobe/LEfbX/131/
var validation = function(){
var err = 0;
err += validate('select_person', "select person.");
err += validate('has_id', "Select whether it has an ID or not.");
if(err == 0){
alert('continue');
} else{
alert('error: ');
}
};
You may also check this part:
$('#select_person:first-child').attr('has_id')
You're trying to find an attribute with the name has_id, which would work for something like this:
<select has_id="some_value" />
I think you mean to select the attr('id') which will return the value of 'has_id':
<select id="has_id" />
Related
I have a button that triggers a kartik dialog.prompt, where text is put in.
I need the input in the dialog to have several rows and line breaking capability (like textarea)
How to change it from a simple text input to textarea?
Here is my javascript:
$("#bulk-email-button-invitations").on("click", function() {
var grid = $("#invitations");
var keys = grid.yiiGridView('getSelectedRows');
if (keys.length >= 1){
krajeeDialog.prompt({label:'Text emailu:', placeholder:'Zadejte text emailu'}, function (result) {
if (result) {
$(location).attr('href', '/educational-event-invitation/bulk-email?' + $.param({invitations: keys, text: result}));
} else {
krajeeDialog.alert('Text emailu nesmí být prázdný!');
}
});
}else{
krajeeDialog.alert("Nejprve vyberte studenty, kterým chcete poslat email!")
}
});
I found that if type is not defined (unlike label and placeholder in my case), it defaults to "text". But I wasn't able to make the dialog render any type other than a simple one-row text input.
Apparently, this is not supported in the extension.
Reason:
The reason is that in the dialog.js where the KrajeeDialog.prototype is defined the function bdPrompt is the one that takes care of the prompt dialog that is to be created and it creates the default field type as input rather than deciding on any of the options or parameters passed to KrajeeDialog.prompt() although you can pass a parameter of name type like
krajeeDialog.prompt({
label:'Text emailu:',
placeholder:'Zadejte text emailu',
type:'password'
},function(){})
but this does not decide if the element will be input or textarea type, this parameter type is passed as the attribute of the input element. See the below code block to understand the reason i explained the third line will always create a field of type input.
File yii2-dialog/assets/js/dialog.js Line 110
if (typeof input === "object") {
$inputDiv = $(document.createElement('div'));
$input = $(document.createElement('input'));
if (input['name'] === undefined) {
$input.attr('name', 'krajee-dialog-prompt');
}
if (input['type'] === undefined) {
$input.attr('type', 'text');
}
if (input['class'] === undefined) {
$input.addClass('form-control');
}
$.each(input, function(key, val) {
if (key !== 'label') {
$input.attr(key, val);
}
});
if (input.label !== undefined) {
msg = '<label for="' + $input.attr('name') + '" class="control-label">' + input.label + '</label>';
}
$inputDiv.append($input);
msg += $inputDiv.html();
$input.remove();
$inputDiv.remove();
} else {
msg = input;
}
So you might need to override the javascript function according to your needs if you want to work it that way.
It is possible to add custom html to krajeeDialog.prompt after all.
In the documentation, kartik-v states:
content: string|object: If set as a string, it is treated as a raw HTML content that will be directly displayed.
So if I replace the original object in my code with a string containing the desired html, it will render my textarea or any other form element.
For example, replace it with a textarea html:
$("#bulk-email-button-invitations").on("click", function() {
var grid = $("#invitations");
var keys = grid.yiiGridView('getSelectedRows');
if (keys.length >= 1){
krajeeDialog.prompt('<textarea>Sample text...</textarea>', function (result) {
if (result) {
$(location).attr('href', '/educational-event-invitation/bulk-email?' + $.param({invitations: keys, text: result}));
} else {
krajeeDialog.alert('Text emailu nesmí být prázdný!');
}
});
}else{
krajeeDialog.alert("Nejprve vyberte studenty, kterým chcete poslat email!")
}
});
My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/
I want to show error validation messages next to the textbox. For that, I have used after() function and inserted a div. But the div gets appended again and again whenever the field is invalid. I just want it once. Can anybody help me with it?
Here's my code:
$(document).ready(function()
{
$("#name").blur(function()
{
var name = $("#name").val();
var txt= /^[A-Za-z\s]+$/i ;
if((txt.test(name) != true))
{
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
$("#one").empty();
}
else
{
$("#one").remove();
}
});
});
You could use HTML 5 field's validity which is the standard.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Your error message here')"
onchange="setCustomValidity('')" />
You should use additional variable to store your state. Try this logic.
$(document).ready(function() {
var flag = false;
$("#name").blur(function() {
var name = $("#name").val();
var txt = /^[A-Za-z\s]+$/i;
if (!txt.test(name) && !flag) {
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
flag = true;
}
else if (flag && txt.test(name)) {
flag = false
$("#one").remove();
}
});
});
I'm making a quiz with a text input. This is what I have so far:
<html>
<head>
<script type="text/javascript">
function check() {
var s1 = document.getElementsByName('s1');
if(s1 == 'ō') {
document.getElementById("as1").innerHTML = 'Correct';
} else {
document.getElementById("as1").innerHTML = 'Incorrect';
}
var s2 = document.getElementsByName('s2');
if(s2 == 's') {
document.getElementById("as2").innerHTML = 'Correct';
} else {
document.getElementById("as2").innerHTML = 'Incorrect';
}
//(...etc...)
var p3 = document.getElementsByName('p3');
if(p3 == 'nt') {
document.getElementById("ap3").innerHTML = 'Correct';
} else {
document.getElementById("ap3").innerHTML = 'Incorrect';
}
}
</script>
</head>
<body>
1st sing<input type="text" name="s1"> <div id="as1"><br>
2nd sing<input type="text" name="s2"> <div id="as2"><br>
<!-- ...etc... -->
3rd pl<input type="text" name="p3"> <div id="ap3"><br>
<button onclick='check()'>Check Answers</button>
</body>
</html>
Every time I check answers it always says Incorrect and only shows the first question. I also need a way to clear the text fields after I check the answers. One of the answers has a macro. Thanks in advance.
The method getElementsByName returns a NodeList, you can't really compare that against a string. If you have only one element with such name, you need to grab the first element from that list using such code instead:
var s1 = document.getElementsByName('s1')[0].value;
To make it more flexible and elegant plus avoid error when you have typo in a name, first add such function:
function SetStatus(sName, sCorrect, sPlaceholder) {
var elements = document.getElementsByName(sName);
if (elements.length == 1) {
var placeholder = document.getElementById(sPlaceholder);
if (placeholder) {
var value = elements[0].value;
placeholder.innerHTML = (value === sCorrect) ? "Correct" : "Incorrect";
} else {
//uncomment below line to show debug info
//alert("placeholder " + sPlaceholder+ " does not exist");
}
} else {
//uncomment below line to show debug info
//alert("element named " + sName + " does not exist or exists more than once");
}
}
Then your code will become:
SetStatus('s1', 'ō', 'as1');
SetStatus('s2', 's', 'as2');
//...
document.getElementsByName('s1') is an array you should use document.getElementsByName('s1')[0] to get certain element(first in this case)
I need to do multiple checks in a jquery condition ...
I am looking for something like this:
IF checkbox_A is Checked then
If input_A is empty then alert('input_A is Required')
else Add a class="continue" to the div below.
<button id="btn1">Continue</button>
Possible?
I normally wouldn't do this as you haven't even shown an attempt to write any code yourself, but I'm in a good mood.
if ($("#checkboxA").is(":checked")) {
if ($("#inputA").val() == "") {
alert("input_A is required");
}
else {
$("#btn1").addClass("continue");
}
}
$(document).ready(function() {
if($("#yourCheckBoxId").is(":checked")) {
if($("#yourInputId").val() == "") {
alert("empty");
}
else {
$("button[id='btn1']").addClass("continue");
}
}
});
yes, it's possible:
$('#checkBoxA').click(function() {
var checkBoxA = $('#checkBoxA');
var textBoxA = $('#textBoxA');
if (checkBoxA.checked())
{
if (textBoxA.val() == "")
{
$('#btn1').removeClass('continue');
alert("No value entered");
textBoxA.focus();
}
else {
$('#btn1').addClass('continue');
}
} else {
$('#btn1').addClass('continue');
}
});
Maybe
if ( document.getElementById('checkbox_A').checked ){
if (document.getElementById('input_A').value == ''){
alert('input_A is Required')
} else {
$('#btn1').addClass('continue;);
}
}
But if you have multiple elements you want to validate you can avoid manual checking of each field and automate by adding an required class to the element that are required..
<input type="text" name="...." class="required" />
now when you want to validate the form you do
// find the required elements that are empty
var fail = $('.required').filter(function(){return this.value == ''});
// if any exist
if (fail.length){
// get their names
var fieldnames = fail.map(function(){return this.name;}).get().join('\n');
// inform the user
alert('The fields \n\n' + fieldnames + '\n\n are required');
// focus on the first empty one so the user can fill it..
fail.first().focus();
}
Demo at http://jsfiddle.net/gaby/523wR/