jQuery & Handling Element ID's - javascript

I have the following code:
function mandatoryField(manF)
{
var fieldId = $(manF).val();
if(fieldId == "")
{
return false;
}
else
{
return true;
}
}
It doesn't work, but this does:
function mandatoryField()
{
var fieldId = $("#element_1").val();
if(fieldId == "")
{
return false;
}
else
{
return true;
}
}
Presume, on my first example, mandatoryField is called as such:
mandatoryField("#element_1")
Why doesn't it work when I try to replace the absolute element ID name with a variable?
Edit:
Most recent code - non-working:
function isAmExSelected()
{
return $("#creditCardType").val() == "American Express";
}
function containsOnlyDigits(str)
{
return str.match(/[^0-9]/) == null;
}
function validateCCNumber()
{
var ccn = $("#creditCardNumber").val();
var onlyDigits = containsOnlyDigits(ccn);
if(isAmExSelected())
{
return ccn.length == 15 && onlyDigits;
}
else
{
return ccn.length == 16 && onlyDigits;
}
}
function mandatoryField(manF)
{
var fieldId = $("#" + manF).val();
return fieldId != "";
}
function registerValidation(id, validateMethod(), errorMethod)
{
$(id).change(function(){
if(validateMethod() == false)
{
errorMethod();
}
});
}
$(document).ready(function(){
registerValidation("#creditCardNumber", validateCCNumber, function(){alert("Invalid Credit Card Number!")});
$('input[type=text][class=mandatory]').blur(function(){
if (mandatoryField(this.id)) {
alert('Field:' + this.id + ' is mandatory!')
}
});
});
Edit 2
I've rewritten the entire thing to look like this:
$('input[type=text][class=mandatory]').blur(function(){
if (!($("#" + this.id).val().length)) {
alert('Field:' + this.id + ' is mandatory!');
}
});
If a text input of the mandatory class blurs, then run the function: if #foo.val() does not have length (i.e. has no text in it), run the alert. I believe it should work, but it does not.

Update your code to so:
function mandatoryField(manF)
{
var fieldId = $("#" + manF).val();
if(fieldId == "")
{
return false;
}
else
{
return true;
}
}
and then try again.

Both pieces of code should work the same irrespective of whether the selector is passed in as an argument, or provided as a literal to $ directly. Also, instead of the if..else, you could do
function mandatoryField(manF) {
var fieldId = $(manF).val();
return fieldId != "";
}

Try this one:
function mandatoryField(manF)
{
if($('#' + manF).val() == "")
{
return false;
}
else
{
return true;
}
}
mandatoryField("element_1");
But this will get you value of element, not it's id. I'm not sure what you are tring to accomplish.
Trigger on field blur option:
$('input[type=text][class=classForMandatoryFields]').blur(function(){
if (mandatoryField(this.id)) {
alert('Field:' + this.id + ' is mandatory!')
}
});

Could you try:
var fieldId = manF.val();
mandatoryField($("element_1"));

Besides your selector problem, you could rewrite your function like this:
function mandatoryField(manF){
return $(manF).val().length;
}
This is, because in JavaScript everything has a truth or false meaning. For numbers, 0 is false.
EDIT:
My test works just fine:
function mandatoryField(manF){
return $(manF).val().length;
}
(...)
<input id="test" value=""/>
<input type="button" value="dd" onClick="alert('length: ' + (mandatoryField('#test'))"/>

Okay this will not work because jquery will assume manF is a DOM object but instead you are passing string.
have you ever tried
var tr = $('#element1') //----------1
alert($(tr).val()) //------------2
tr is actually a dom object
UPDATE::
why don't you try this one
//some code on some event
if(!check_mandatory())
//do something else
else do another thing
//some code on some event
and the function
function check_mandatory()
{
$('.mandatory').each(function{
if($(this).val() == ""){
alert($(this).attr("name") + "required");
//or you can use id or any attrib
return false;
}
})
}
note code might not work not tested, if it did not work then let me know

Related

How can I disable button and change the button text on this code?

I dont know very well jquery/javascript and I am having problems with the code below.
After the form validation steps, the button is disabled but the form is not submited. Where is wrong?
$(function() {
$('.form_error').hide();
$("#submit_button").click(function() {
var tempo_show = 400
$('.form_error').hide();
var card_name = $("input#card_name").val();
if (card_name == "") {
$("span#validation_card_name").fadeIn(tempo_show);
//alert("Informe o Nome do titula do cartão");
$("input#card_name").focus();
return false;
}
var owner_birthdate = $("input#owner_birthdate").val();
if (owner_birthdate.length < 8) {
$("span#validation_owner_birthdate").fadeIn(tempo_show);
//alert("Informe o Nome do titula do cartão");
$("input#owner_birthdate").focus();
return false;
}
// here is where I can't make work
$(this).html('Processando...');
$(this).attr('disabled', true);
});
});
I think this $("input#card_name").val(); should be this $("#card_name").val();. The reason is you don't need to specify the element type when you want to get them by ID. Make similar changes to the rest of the code as well. Try adding $("#YOURFORMID").submit() at the end.
Try this:
$(function() {
$('.form_error').hide();
$("#submit_button").click(function() {
var tempo_show = 400
$('.form_error').hide();
var card_name = $("#card_name").val();
if (card_name == "") {
$("#validation_card_name").fadeIn(tempo_show);
//alert("Informe o Nome do titula do cartão");
$("#card_name").focus();
return false;
}
var owner_birthdate = $("#owner_birthdate").val();
if (owner_birthdate.length < 8) {
$("#validation_owner_birthdate").fadeIn(tempo_show);
//alert("Informe o Nome do titula do cartão");
$("#owner_birthdate").focus();
return false;
}
// here is where I can't make work
$(this).html('Processando...');
$(this).attr('disabled', true);
$("#YOURFORMID").submit();
});
});

Javascript save , erase and reload input value

I have a problem with my Script. I want to do the following steps in this order:
1. Save the text in the input field.
2. Delete all text in the input field.
3. Reload the same text that was deleted before in the input field.
The problem with my script is that the ug()- function writes undefined in my textbox instead of the string that should be stored in var exput. The alert(exput) however shows me the correct content.
Help would be very much appreciated. And I'm sure there is better ways to do that, I'm quite new to this stuff.
HTML
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();deleter();ug()" />
Javascript
function merker() {
var merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
Your code is calling merker(); deleter(); ug(); in the onclick event, but ug() is already called by merker(). You should be doing this instead:
function merker() {
var merkzeug = document.getElementById('a').value;
deleter();
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();" />
I changed Your Javascript:
function merker() {
merkzeug = document.getElementById('a').value;//global variable without var
ug();//why You use it here? I think only for test. So delete it after.
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug() {
alert(merkzeug);
document.getElementById('a').value =merkzeug;
};
Problems with your code:
method ug was used with argument and without argument ( i changed to without )
to restore deleted value it must be saved to some variable, i saved to global merkzeug variable - this is not good practice but sufficient in this case
next i used merkzeug to restore value in textarea in ug() function
i do not know why You using ug() two times? maybe delete one of them is good thing to do.
In plunker - https://plnkr.co/edit/fc6iJBL80KcNSpaBd0s9?p=info
problem is: you pass undefined variable in the last ug function:
you do: merker(value) -> ug(value); delete(); ug(/*nothing*/);
or you set your merkzeung variable global or it will never be re-inserted in your imput:
var merkzeug = null;
function merker() {
merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
if (typeof exput === 'undefined') exput = merkzeung;
alert(exput);
document.getElementById('a').value = exput;
};

Cannot run function

Important note so people don't get caught out (like I did): This may look like jQuery, but it is not.
Honestly, I should've known better. I use $ for stuff other than jQuery. Oh well. Lesson learned! ~Niet the Dark Absol
Code :
(HTML):
<html>
<head>
<script src="selector.js"></script>
</head>
<body>
<label id="id">A label</label>
<script>
$("label #id").clicked(function(){
alert("ASDASD");
});
</script>
</body>
</html>
(JS):
/*
NAME : SELECTOR.JS
*/
function $(attr){
// Removed space in front of the variable
while(attr.charAt(0) == " "){
attr = attr.substr(1);
if(attr == ""){
return 0;
}
}
// Completed the query
if(attr.length > 1){
return Array.prototype.slice.call(document.querySelectorAll(attr));
}else{
if(attr.length == 1){
return new Object(document.querySelector(attr));
}else{
return null;
}
}
}
Object.prototype.clicked = function(script){
if(typeof(this) == "object"){
if(this.constructor == Array){
for(var i = 0; i < this.length; i++){
this[i].onclick = script;
}
}else{
if(this.constructor == Object){
console.log("SINGLE OBJECT : " + this);
console.log("SINGLE OBJECT : ONCLICK : " + this);
this.onclick = script;
}else{
console.log("ERROR : this.constructor is not 'Object' or 'Array'.");
return null;
}
}
}else{
console.log("ERROR : typeof(this) is not 'Object'.");
return null;
}
return this;
};
When I clicked the label, I cannot get the alert box seen.
What should I do? The file name is selector.js, for the js file.
I need the function to be ran. Pls help!
I think this is the minimized code.
The space is wrong, instead of $("label #id") it needs to be $("label#id"). With the space between label and #id you're searching for an element inside a label with id="id", without the space you're searching for a label with id="id".
The function
.clicked()
you used, is not a valid jQuery function. The one you are looking for is:
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
See here:
http://api.jquery.com/click/

remove value from the list

I have a list of checkboxes. Upon clicking on each of the checkboxes i am adding the value to the hidden variable. But the question is if I want to remove the value from the list upon unchecking the checkbox . How this piece cab be done
here is the hidden form variable
<input name="IDList[]" type="hidden" id="IDList" value="" />
and the jquery
$(".myCheckboxClass").change(function() {
var output = 0;
$(".myCheckboxClass").change(function() {
if ($(this).is(":checked")) {
output += ", " + $(this).val();
} else {
output = $.grep(output, function(value) {
return value != $(this).val();
});
}
$("#IDList").val(output);
});
});
Something like this: (demo) http://jsfiddle.net/wesbos/5N2kb/1/
we use an object called vals to store the info. ADding and removing as we check/uncheck.
var vals = {};
$('input[type=checkbox]').click(function() {
var that = $(this);
if (that.is(':checked')) {
console.log(this.name);
vals[this.name] = "In your Object";
}
else {
delete vals[this.name];
}
console.log(vals);
});
Following your logic, you could do this:
$('#IDList').data('value', []);
$(".myCheckboxClass").change(function() {
var list = $('#IDList').data('value');
if ($(this).is(":checked")) {
list.push($(this).val());
} else {
var indexToRemove = list.indexOf($(this).val());
list.splice(indexToRemove, 1);
}
$('#IDList').val(list);
});
But if you only care about the value of #IDList upon data submission or other actions, you probably want to consider an alternative approach: collating the checked values when you need them.
$('#form').submit(function() {
var list = $('input.myCheckboxClass:checked', this).map(function() {
return $(this).val();
}).get();
$('#IDList').val(list);
});
See both of the above in action: http://jsfiddle.net/william/F6gVg/1/.

Two scripts Javascript doesn't work together

I have two scripts in a file active_form.js
The first script hides a text entry when a radiobutton is checked and the second does the same thing when a value is selected in a list.
When there are alone, the both work but together my function GereControleRadio do nothing.
edit : the two scripts are called in the same form.
The code of my scripts :
function GereControleRadio(Controleur, LabelControle, Controle, Masquer) {
var objLabelControle = document.getElementById(LabelControle);
var objControle = document.getElementById(Controle);
if (Masquer=='1') {
objControle.style.visibility=(objControleur.checked==true)?'visible':'hidden';
objLabelControle.style.visibility=(objControleur.checked==true)?'visible':'hidden';
}
else {
objControle.disabled=(objControleur.checked==true)?false:true;
objLabelControle.disabled=(objControleur.checked==true)?false:true;
}
return true;
};
function GereControleList(LabelControle, Controle, val) {
var objLabelControle = document.getElementById(LabelControle);
var objControle = document.getElementById(Controle);
if (val != '1% Patronal') {
objControle.style.visibility='hidden';
objLabelControle.style.visibility='hidden';
}
else {
objControle.style.visibility='visible';
objLabelControle.style.visibility='visible';
}
return true;
};
The .js is called in my view.yml
And I call the functions :
echo $form['etage']->render(array("onCLick" => "GereControleRadio('logement_etage_Etage', 'numetage_label', 'numetage_form, '1');"))
echo $form['reservataire']->render(array("onChange" => "GereControleList('patronal', 'patronal_form', 'this.value');"))
I believe you just have 2 functions with conflicting global scope variable names. Try replacing "GereControleList" with this...
function GereControleList(LabelControle, Controle, val) {
var objLabelControle_ = document.getElementById(LabelControle);
var objControle_ = document.getElementById(Controle);
if (val != '1% Patronal') {
objControle_.style.visibility='hidden';
objLabelControle_.style.visibility='hidden';
}
else {
objControle_.style.visibility='visible';
objLabelControle_.style.visibility='visible';
}
return true;
};
I have found the error : in GereControleRadio, I have deleted a line.
var objControleur = document.getElementById(Controleur);

Categories

Resources