how to call another function in javascript? - javascript

how do i call the doSubmit() function from the conFirmUpload() when the confirm msg box is true?
<script type="text/javascript">
function confirmUpload() {
if (confirm("Are you sure want to upload '" + document.getElementById("txtWS").value + "' ?") == true) {
return true;
}
else
return false;
}
function doSubmit(btnUpload) {
if (typeof(Page_ClientValidate) == 'function' && Page_ClientValidate() == false) {
return false;
}
btnUpload.disabled = 'disabled';
btnUpload.value = 'Processing. This may take several minutes...';
<%= ClientScript.GetPostBackEventReference(btnUpload, string.Empty) %>;
}
</script>

var btnUpload = document.getElementById('buttonId');
doSubmit(btnUpload);
Put that in your if-block. Make sure the button has an ID.

Without knowing more What about this?
function confirmUpload(btnUpload) {
if (confirm("Are you sure want to upload '" + document.getElementById("txtWS").value + "' ?") == true) {
doSubmit(btnUpload);
}
else
return false;
}

function confirmUpload() {
if (confirm("Are you sure want to upload '" + document.getElementById("txtWS").value + "' ?") == true) {
var btnUpload = document.getElementById('<%= btnUpload.ClientID %>');
doSubmit(btnUpload);
}
}

Change the method prototype as
function confirmUpload(obj) {
//Do some thing
}
Where obj the the button you are clicking on
Call this method as
**onclick="javaScript:confirmUpload(this)"**
Now in that if part call another method like
if (confirm("Are you sure want to upload '" + document.getElementById("txtWS").value
+ "' ?") == true) {
doSubmit(obj);
}

Related

prevent function from recalling itself at the last statement of the function in java script

I've been learning javascript and jquery and I've encountered a problem when I'm trying to validate my form fields using a jquery function. The problem is its working fine the first two times it is called (when I press the update button for a specific element )and whenever I'm trying to call it a third time (by pressing the update button for the same element as earlier ) it is calling itself but I clearly did not mention any recursive calls and am not calling it within the function again. I'm not sure why it is calling itself. Kindly help me out. I will be attaching the fiddle. After triggering reset in main.updateData(Object.assign({}, main.newObject), keys); in the third time its showing the name empty error which shouldn't be happening.
I've tried giving breakpoints and inspecting the reason behind this weird behaviour but I couldn't
The name field should show an error only when it is empty but third time it is showing error even when it is not empty
FIDDLE
validateFormData: function(value, keys, idCount) {
var keyIndex = 0;
main.newObject[keys[keyIndex++]] = idCount;
if (value == "update") {
main.newObject[keys[0]] = $(".active-contact").attr('id');
//alert("new updated id is " + main.newObject[keys[0]]);
}
var validElementsCount = 0;
var alphabet_pattern = /^[a-z]+\s*/i;
var email_pattern = /[a-z]{0,}[0-9]{0,4}[.]{0,1}[0-9]{0,4}[a-z]{0,8}[0-9]{0,4}[#][a-z]{0,20}[.](com)/i;
var number_pattern = /^[0-9]{10}$/;
var website_pattern = /^(www)[.][a-z]{1,20}[.](com)$/i;
/*Validating the form inputs against the regex pattern*/
if ($("#employee-name").val() == "") {
$("#employee-name-error").text("name cannot be empty");
} else if (!alphabet_pattern.test($("#employee-name").val())) {
$("#employee-name-error").text("Only alphabets are allowed");
} else {
validElementsCount++;
$("#employee-name-error").text("");
main.newObject[keys[keyIndex++]] = $("#employee-name").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex-1]]) + " key is " + keys[keyIndex-1]);
}
//employee email validation
if (email_pattern.test($("#employee-email").val()) || $("#employee-email").val() == "") {
$("#employee-email-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-email").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex - 1]]) + " key is " + keys[keyIndex - 1]);
} else {
$("#employee-email-error").text("Follow email pattern");
}
//employee mobile validation
if (number_pattern.test($("#employee-mobile").val()) || $("#employee-mobile").val() == "") {
$("#employee-mobile-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-mobile").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex - 1]]) + " key is " + keys[keyIndex - 1]);
} else {
$("#employee-mobile-error").text("Only 10 digit number is allowed");
}
//employee landline no validataion
if (number_pattern.test($("#employee-land-line").val()) || $("#employee-land-line").val() == "") {
$("#employee-land-line-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-land-line").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex - 1]]) + " key is " + keys[keyIndex - 1]);
} else {
$("#employee-land-line-error").text("Only 10 digit number is allowed");
}
//employee website validation
if (website_pattern.test($("#employee-website").val()) || $("#employee-website").val() == "") {
$("#employee-website-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-website").val();
} else {
$("#employee-website-error").text("Follow website pattern");
}
main.newObject[keys[keyIndex++]] = $("#employee-address").val();
if (validElementsCount == 5) {
if (value == "add") {
main.addEmployeeClick(Object.assign({}, main.newObject));
$(".employee-details-form").trigger("reset");
} else if (value == "update") {
//alert("new object is " + JSON.stringify(Object.assign({}, main.newObject), keys));
main.updateData(Object.assign({}, main.newObject), keys);
$(".employee-details-form").trigger("reset");
}
}
},
You can add .off() before #update-employee-btn click event binding in line 34.
$("#update-employee-btn").off().click(....)
Let me know if it works for you as well.

How to add img to every message created on enter using Jquery?

I can't figure this out. It's probably something small which I can't process at the moment. I am a beginner in this, sorry.
Now I am working on this chat, every time I press enter a class is being created with username and message.
On the left side of username, I want to put this img profile which the user can chose, or just use the default.png.
I want the picture to remain on the left side of his name before deleting.
Here is some of the code:
<script>
$("#message").keypress(function(e) {
var test = $("#Uname").val()
var valmsg = $('#message').val();
var poza = $('<img src="http://dev.alurosu.com/bobo/chat/data/img/admin/default.png">');
if(e.which == 13 && valmsg.trim() == "" ){
e.preventDefault();
alert('Please type a message to send');
} else if (e.which == 13) {
$("#chat").append("<div class='mesaj' >" + test + ':' + valmsg + "</div>");
$("#chat").append(poza);
$('#message').val('');
e.preventDefault();
}
});
</script>
And here is Jsfiddle but I couldn't upload the complete code.
And here is a screenshot exemple
Hope you can explain to me somehow. Thank You.
else if (e.which == 13) {
var imgpath = '<img src="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/user-group-512.png" width="30px" height="30px" style="float:right">';
$("#chat").append("<div class='mesaj' >" + test + ':' + valmsg + imgpath +"</div>");
$('#message').val('');
}
use this code ..
I assume you want the image to be followed by the Username,so you should be using Prepend.
$('div.mesaj').prepend(yourimage);
Do make sure the image path is correct.
$(document).ready(function () {
$("#Uname").click(function () {
$("#popUp").show();
});
$(".pophide").click(function () {
$("#popUp").hide();
});
// display previous stored username, if set
var prevUname = localStorage.getItem("user");
if (prevUname !== null) {
$("#Uname").val(localStorage.getItem("user"));
}
$("#save").click(function () {
var valoare = $("#userSet").val();
if (typeof (Storage) !== "undefined") {
// Store
localStorage.setItem("user", valoare);
// Retrieve
$("#Uname").val(localStorage.getItem("user"));
} else {
$("#Uname").val("Sorry, your browser does not support Web Storage...");
}
});
$("#message").keypress(function (e) {
var test = $("#Uname").val();
var image = "<img src='https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSlk3gZnCZExtx8vMg5ykXThHnVmk4SjFZpwYysmCiuBXxQFXQhmg' />";
var valmsg = $('#message').val();
if (e.which == 13 && valmsg.trim() == "") {
e.preventDefault();
alert('Please type a message to send');
} else if (e.which == 13) {
$("#chat").append("<div class='mesaj' >" + test + ':' + valmsg + image + "</div>");
$('#message').val('');
}
});
$("#chat").on("click", ".mesaj", function () {
console.log("Merge click clasa");
$("#yes").click(function () {
$(".mesaj").remove();
$("#delPop").hide();
});
$("#delPop").show();
$("#no").on("click", function () {
$("#delPop").hide();
});
});
});
Add CSS
#chat img {
float: right;
height: 30px;
}

Check if input fields are filled out in a form

I have a form myForm and I want to check if specific input field are filled out before sending the form. I'm very new to JavaScript so I don't really know what I did wrong. Any help is welcomed.
function validateForm() {
var validate = true;
var alert_string = "";
var children = $("#myForm").children("input");
console.log(children.size());
for(var i = 0; i < children.length ; i++){
if(children[i].attr(id).substring(0,8) != "ABC_FLAT"){
if(children[i].attr(id) == null || children[i].attr(id) == ""){
validate = false;
alert_string = alert_string.concat(childrern[i].attr(id)).concat(", ");
}
}
}
alert_string = alert_string.concat("must be filled out !");
if(validate == false){
alert(alert_string);
return false;
}
return true;
}
children[i].attr(id) == "" // wrong
You don't have to check whether their ids are null, you have to check whether their values are empty :)
if(children[i].value == "")
Since you are already using jQuery, you can simplify that code to a great extent. For example a simple "all fields filled" check can be
var flag=0;
$('#myForm').each(function() {
if ( $(this).val() === '' )
flag=1;
});
if you'll use jQuery, you can check the input fields if empty AND trap also white space/s. Add a class to all input fields , e.g. class="required" and add attribute fieldname with respective value for each input field.
var requiredFields = "";
$("#myForm").find('.required').each(function () {
if ($(this).val().trim().length == 0) {
requiredFields += " - " + $(this).attr("fieldname") + "\n";
}
});
if (requiredFields != "") {
alert("Please enter the following required field(s): \n" + requiredFields);
} else {
//save here
}
You can use required like <input required type="text" name="email" id="log" /> or use jQuery like
$("form").submit(function() {
var has_empty = false;
$(this).find('input').each(function() {
if(! $(this).val()) {
has_empty = true;
return false;
}
});
if(has_empty){return false;}
});

set focus to textbox form element following Validation

I have a number of fields on a form that I perform Validation on, which I then want to Focus on if the validation fails. The Validation works fine, i.e. rtnStr, but the focus() just won't land on any of the textbox fields, i.e. vCtrl. It remains on the Submit button.
<script language="javascript">
function ValidateForm() {
var rtnStr = "";
var vCtrl = "";
//Contact Details //
if (document.contactform.txtforename.value == "") {
rtnStr = rtnStr + " - Please enter your Forename.\n"
if (vCtrl == "") {
vCtrl = "txtforename";
}
}
if (document.contactform.txtSurname.value == "") {
rtnStr = rtnStr + " - Please enter your Surname.\n"
if (vCtrl == "") {
vCtrl = "txtSurname";
}
}
if (rtnStr != "") {
alert(rtnStr)
window.setTimeout(function () {
document.getElementById(vCtrl).focus();
}, 0);
return false;
}
else {
return true;
}
}
</script>
The problem is that vCtrl is a string which is the name of a form and not the id which document.getElementById(vCtrl).focus() is looking for. The way to fix this is to make vCtrl store the DOM element instead of a text string.
<script language="javascript">
function ValidateForm() {
var rtnStr = "";
var vCtrl = "";
//Contact Details //
if (document.contactform.txtforename.value == "") {
rtnStr = rtnStr + " - Please enter your Forename.\n"
if (vCtrl == "") {
vCtrl = document.contactform.txtforename;
}
}
if (document.contactform.txtSurname.value == "") {
rtnStr = rtnStr + " - Please enter your Surname.\n"
if (vCtrl == "") {
vCtrl = document.contactform.txtSurname;
}
}
if (rtnStr != "") {
alert(rtnStr)
vCtrl.focus();
return false;
}
else {
return true;
}
}
</script>
jsfiddle

Preventing code replication in javascript by combining these functions

So I have two jquery functions that bassically do the same, but on 2 seperate containers. Is there a way to combine these two functions.
$('#autobid-list .auction-button').click(
function(){
if($(this).attr('summary') == 'autobid-button'){
$(this).parents('li').addClass('none');
}else if($(this).attr('summary') == 'watchlist-button'){
if($(this).hasClass('watchlist-1')){
$(this).parents('li').clone().appendTo('#watchlist-list');
}else{
$('#watchlist-list .auction-' + $(this).parents('table').attr('summary')).parents('li').addClass('none');
}
}
}
);
$('#watchlist-list .auction-button').click(
function(){
if($(this).attr('summary') == 'watchlist-button'){
$(this).parents('li').addClass('none');
}else if($(this).attr('summary') == 'autobid-button'){
if($(this).hasClass('autobid-1')){
$(this).parents('li').clone().appendTo('#autobid-list');
}else{
$('#autobid-list .auction-' + $(this).parents('table').attr('summary')).parents('li').addClass('none');
}
}
}
);
These two do bassically the same, the only change is the input of either 'autobid' or 'watchlist'
Obvious answer:
$('#watchlist-list .auction-button').click(function(){
whatever.call(this,'watchlist', 'autobid');
});
$('#autobid-list .auction-button').click(function(){
whatever.call(this,'autobid', 'watchlist');
});
function whatever(one, two){
if($(this).attr('summary') == one + '-button'){
$(this).parents('li').addClass('none');
}else if($(this).attr('summary') == two + '-button'){
if($(this).hasClass(two + '-1')){
$(this).parents('li').clone().appendTo('#' + two + '-list');
}else{
$('#' + two + '-list .auction-' + $(this).parents('table').attr('summary')).parents('li').addClass('none');
}
}
}
Though some rethinking is probably better.
EDIT: Oops, fixed.
Sure, just determine which one was clicked and assign a variable according to that. You can select several elements at once when you separate them with commas:
$('#watchlist-list .auction-button, #autobid-list .auction-button').click(function() {
// Determine which button was clicked, you might want to adjust this as needed.
var type = $(this).closest('#autobid-list').length > 0 ? 'autobid' : 'watchlist';
// Then just replace 'autobid' and 'watchlist' with 'type'
if($(this).attr('summary') == type+'-button') {
$(this).parents('li').addClass('none');
} else if($(this).attr('summary') == type+'-button') {
if($(this).hasClass(type+'-1')) {
$(this).parents('li')
.clone()
.appendTo('#'+type+'-list');
} else {
$('#'+type+'-list .auction-' + $(this).parents('table').attr('summary'))
.parents('li')
.addClass('none');
}
}
});
Could this work? Make a function that returns a function:
function MyFunction(type) {
return function(){
if($(this).attr('summary') == type + '-button'){
$(this).parents('li').addClass('none');
}else if($(this).attr('summary') == type + '-button'){
if($(this).hasClass(type + '-1')){
$(this).parents('li').clone().appendTo('#' + type + '-list');
}else{
$('#' + type + '-list .auction-' + $(this).parents('table').attr('summary')).parents('li').addClass('none');
}
}
}
}
$('#autobid-list .auction-button').click(MyFunction('autobid'));
$('#watchlist-list .auction-button').click(MyFunction('watchlist'));

Categories