JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.

Share tech news, updates, or what's on your mind.

Sign up to Post

I have this site with a navigation bar with a dropdown. On the other site i have a select with two values.
This is the dropdown:
         <button class="dropbtn">Login</button>
                    <div class="dropdown-content">
                        <a class = "teacher" href="login">Teacher Login</a>
                        <a class = "student" href="login">Student Login</a>
                    </div>

Open in new window

And this is the select i am using:
    <form class = "login" action="/login" method="post">
        <div class="form-group">
            <select class="form-control" name="role">
                <option disabled selected value="role">Role</option>
                        <option value="teacher">Teacher</option>
                        <option value="student">Student</option>
            </select>

Open in new window

So my question is : how can i  make it that if the user clicks on student login the select will stand on value "student" and the other way around?
The select is on a different page then the login dropdown so that makes it hard for me.
0
I need to figure out how to add some additional markers to the embedded google map that's on this page:

http://benderslandingestates.com/contact.html

I've already figured out how to add the image overlays that display the addresses when clicked.  All I have to do is add an additional unordered list item similar to the following and then change it's X and Y coordinates and the image file name:

<li data-x="-95.380427" data-y="30.115507" data-basic="images/BLE-map-marker.png" data-active="images/gmap_marker_active.png">
                    <p>3440 Riley Fuzzel Rd, Suite 150, Spring, TX 77386 <span>Call 281-364-7440</span></p>
 </li>

Open in new window


What I can't seem to figure out is how to insert some additional red markers by updating the Javascript:

http://benderslandingestates.com/js/jquery.rd-google-map.js

The section that needs to be re-written -- I suspect -- is the following:

defaults = {
            map: {
                x: -95.3726757,
                y: 30.1183008,
                zoom: 13
            },
            locations: []
        };

Open in new window


.. but I'm not entirely sure.  Can anyone here be of any assistance?  How would I add - say - 2 additional X / Y coordinates to the Javascript so that it shows 2 additional markers in the embedded Google map?

Thanks,
-- Yvan
0
Trying to get a div to slide in from the left and stick to the bottom of the page, after a 4 second delay on page load.

The div appears on page load, no delay, or slide-in effect.

html
<div id="slidebox" class="show modal">
    <!-- ACF ad url here -->
    <a href="#">
    <!-- ACF img here -->
        <img src="https://upload.wikimedia.org/wikipedia/commons/2/24/Ad-MediumRectangle-300x250.jpg" alt="-ad" width="300" height="250">
    </a>
</div><!-- /.slidebox -->

Open in new window


CSS
#slidebox.show {
  left: 0;
  -webkit-transition: 0.5s ease-in-out;
  transition: 0.5s ease-in-out;
}
#slidebox {
  max-width: 300px;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: -430px;
  z-index: 10;
  -webkit-transition: 0.5s ease-in-out;
  transition: 0.5s ease-in-out;
}

.show {
  display: block;
}

Open in new window



js
jQuery(document).ready(function($) {
  setTimeout(function() {
    $('#slidebox').delay(4000).fadeIn(500);
  }, 4000); // milliseconds. set to 10 seconds.
});

Open in new window

0
Getting the following error in my js script. :  Uncaught TypeError: $ is not a function

$(document).ready(function() {
    setTimeout(function() {
      $('#data-ad-popup').modal('show');
    }, 10000); // milliseconds. set to 10 seconds.
});

Open in new window


Not sure how to fix it?
0
Hi,
I start by saying this is the first project I have ever published and apologize in advance if I give you too much or too little information.
So, I published this MVC project to a business server.  It works but the data in the datatable is not showing. Although, when I just debug in Visual Studio there is data.
This project has 2 tabs:  
The first tab is to show the datatable in question which uses Entity Framework;  
The second tab also has a datatable(a yadcf) which shows data that is accessed via Ado.Net.
Data in the first tab does not show, while it does in the second tab.  


The datatable on the first tab references to this link:
 <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>

While for the second tab I imported the yadcf datatable. Below is how I reference to it:
<script src="~/Yadcf/jquery.dataTables.yadcf.js"></script>  


Also, when I do F12 under the "Elements" I can see the references to the datatables(see attached photo).  Plus it looks like the datatable and its functionalities(search box, paging, column names) show up but without any data in it.


IN CASE YOU WANT TO SEE IT, THIS IS THE CODE OF THE INDEX PAGE WHICH INCLUDES THE DATATABLE:
`
@{
    ViewBag.Title = "Index";
}

<ul class="nav nav-tabs">
    <li class="active"><a data-toggle="tab" href="#firstTab">View All</a></li>
    <li><a data-toggle="tab" href="#secondTab">Add New</a></li>
  

Open in new window

0
Hello experts.  I am having some trouble running one of the group projects we created in our bootcamp.  If I may, describe the issue and can you recommend which additional files to attach to help with the detective work?

This was a working project that we presented(it was on a different laptop than mine).  I pulled it down from Github onto my laptop.  I worked through a few roadblocks and I do have it running on my localhost. Unfortunately, the html page that is loaded is blank.  When I open the html file in a Sublime  there is no markup in it.  I attached the index.html file.  There are comments in it I do not understand.  I was responsible for the backend while another team member took care of the frontend

1)
Here is what I have in the server.js file for the html page:

app.get(function(req, res) {
   res.sendFile(path.join(__dirname, "./client/public/index.html"));
});

2)
I attached a screen print of the browser console when the index.html file opens empty.







Thank you for your patience and help,
Ed
0
Hi,
I published a MVC project to a business server.  It works but the data in the datatable is not showing.
Although, when I just debug in Visual Studio there is data.
This project has 2 tabs:  
The first tab is to show the datatable in question which uses Entity Framework;  
The second tab also has a datatable which shows data that is accessed via Ado.Net.
Data in the first tab does not show, while it does in the second tab.  


Could the problem be that while the datatable on the first tab references to this link
 <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>

while for the second tab I imported the yadcf datatable
<script src="~/Yadcf/jquery.dataTables.yadcf.js"></script>   ?



FYI, when I published I used the below:

UNDER CONNECTION:
Publish method: Web Deploy
Server:  (Business Server Name)
Site name:  HelpDeskSupport
Username:  myUsername
Password:  myPassoword

UNDER SETTINGS:
Under "DBModel" as the datasource I added the SQL Server name with its username and password.
I checked the "Use this connection string at runtime..."



Could you please help me figure out what I have done wrong? Thank you.
0
My login form opens in a modal window (Lightview, which is a jQuery modal). The author has abandoned support, but the modal works great for multiple needs.

I keep a variable, which holds the full path to the current page. On successful login, which is authenticated with an AJAX script, I simply do a relocate to the current page as "parent". That page needs to refresh in order to note the user is logged in and provide a logout button. But it also needs to pull up another model with menu selections for the logged in user. In order to open that menu, I sent a variable to the url, which is picked up in the footer. This all works fine in other browsers, but not in IE11.

So, the process is
1. User presses login button. This brings up the login form in Lightview. (Full path of CurrentPage is held in variable
2. Form is submitted to an AJAX authentication.
3. On success, location is directed back to the current page using
   window.parent.location.href = data.CurrentPage+"?Exp=1";

Open in new window

In browsers other than IE11, this closes the model window, refreshes the current page, the Exp is picked up by a javascript function, and the logged-in menu appears in another modal.

I have tried every way imaginable, including replace, assign, window.top ... nothing seems to work in IE11. It simply does nothing, The page does not relocate and the url does not go to the address bar. Even tried history.go(-1). Any known solutions to this problem?
0
Hello Experts,

Need some help in calculating specific choices selected in radio button groups. I've search the net but not finding what I need. So have 18 radio button groups. One group for each 18 rows of questions and three choices (columns) in each row for Lower Risk, Moderate Risk and Higher risk. The naming convention looks like this:
Group 1: Risk1 Choices: LwrRsk1, ModRsk1, HighRsk1
Group 2, Risk2 Choices: LwrRsk2, ModRsk2, HighRsk2
Group 3: Risk3 Choices: LwrRsk3, ModRsk3, HighRsk3, etc.

I need a way to add up all the choices select for LwrRsk choices, all the values for the ModRsk choices and sum the values for all the HighRsk choices selected and display the value of the sums in respected text boxes called Lower Risk Total, Moderate Risk Total, High Risk Total.

Hoping someone can help me with this.

Attached is the form I am working with....

Thanks!
Suicidal_Risk_Screening_Tool-Fillabl.pdf
1
RDLC has issues when running on Internet Explorer 11. How do I identify if a client side computer connected to our website has IE 11. I've read things that say MS tries to hide this by calling it Trident and then vs 11.

Javascript, Jquery, C# all okay for examples
0
Hi Experts,

I have a Microsoft Failover Cluster with 2 nodes and a Quorum disk (file share witness). Lately when I've taken one node offline for maintenance the cluster has shutdown all my VM's, I've had to reconnect to the cluster and then my VM's restart and come online. I always test the FSW before I take a node server offline and it always responds. Right now I can no longer trust the cluster. Below are the 2 events recorded...

Critical

File share witness resource 'File Share Witness' failed to arbitrate for the file share '\\<SERVERNAME>\WitnessCluster2'. Please ensure that file share '\\<SERVERNAME>\WitnessCluster2' exists and is accessible by the cluster.

Error

Cluster resource 'File Share Witness' of type 'File Share Witness' in clustered role 'Cluster Group' failed.

Based on the failure policies for the resource and role, the cluster service may try to bring the resource online on this node or move the group to another node of the cluster and then restart it.  Check the resource and group state using Failover Cluster Manager or the Get-ClusterResource Windows PowerShell cmdlet.


How do I stop this happening on my cluster, it does not make sense because the FSW is available and online but as soon as I restart a host node my cluster falls apart and its a real problem when you have 20 VM's that depend on it working.

The 2 nodes are running with Windows Server 2012 R2 Datacenter
The FSW is located on a server running …
0
This is my "is-auth.js" file:

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
	//console.log(req.get(Authorization));
	const authHeader = req.get('Authorization');
	if(!authHeader) {
		const error = new Error('Not Even Working');
		error.statusCode = 401;
		throw error;
	} else {
		const token = authHeader.split(' ')[1];
		let decodedToken;
		try {
			decodedToken = jwt.verify(token, 'secret');
		} catch (err) {
			err.statusCode = 500;
			throw err;
		}
		if(!decodedToken) {
			const error = new Error('Not Authenticated');
			error.statuscode = 401;
			throw error;
		}
		req.userID = decodedToken.userId;
		next();
	}
};

Open in new window


If you notice the line, "//console.log(req.get(Authorization));," - if I un-commented that line, I would get an error that said, "message: "Authorization is not defined."

I'm thinking that's because the "console.log..." thing can't be referenced in the code the way that I have it. And what makes it hard to "see," is that unless you're aware of how a method needs to be crafted and WHERE you can actually do a "console.log," you're going to beat your head up against the way looking for another error.

Am I correct?

Is the placement of "console.log(req.get(Authorization))" toxic? Is that a dealbreaker? Will that break the code?

And what's a good rule of thumb for "console.log" as far as where you can put it within a method and not be writing code that's going to break however sound it might otherwise be?
0
Here's the code:

exports.createPost = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    const error = new Error("Validation failed, entered data is incorrect.");
    error.statusCode = 422;
    throw error;
  }
  if (!req.file) {
    const error = new Error("No image provided");
    errorStatusCode = 422;
    throw error;
  }
  const imageUrl = req.file.path.replace("\\", "/");
  const title = req.body.title;
  const content = req.body.content;
  const post = new Post({
    title: title,
    content: content,
    imageUrl: imageUrl,
    creator: req.userId
  });
  post
    .save()
    .then(result => {
	  return User.findById(req.userId);
	})
      res.status(201).json({
        message: "Post created successfully",
        post: result
      });
    })
    .catch(err => {
      if (!err.statusCode) {
        err.statusCode = 500;
      }
      next(err);
    });
};

Open in new window


This is a working piece of code that belongs to a Node.js tutorial that I'm going through.

Not wanting to just "cut and paste," I found myself wondering about "return."

I've been operating under the impression that anytime you use "return," you're putting the breaks on within your functionality and nothing else fires beyond that point.

I'm getting that from definitions such as this:

The return statement stops the execution of a function and returns a value from that function.
( https://www.w3schools.com/jsref/jsref_return.asp)

I'm savvy enough to appreciate the utility of what's happening above in that I'm running the "User.findById(req.userID)" query, but the fact that the result is being "returned" made me want to run this past some greater minds that my own and get some clarification on what "return" means in this instance in that it's obviously not compelling the remainder of the code to cease.

Is there a more comprehensive definition of "return" that makes the way in which it's used in this context make sense?
0
We've been asked to download a project and be ready to comment intelligently in a meeting tomorrow, so I'm trying to get this app up and running on my local box, but I'm running into errors that I've not encountered before.

Here is the error as it appears on my terminal:

Listening on PORT: 3000
(node:3316) UnhandledPromiseRejectionWarning: MongoError: not authorized on test to execute command { insert: "system.indexes", documents: [ { ns: "test.user_sess
ions", key: { expires: 1 }, name: "expires_1", expireAfterSeconds: 0, unique: false } ], ordered: true, writeConcern: { w: "majority" }, lsid: { id: UUID("9674b2b
b-4da6-401a-9d90-7b0f35ace911") }, readConcern: { afterClusterTime: Timestamp(1579010568, 1) }, $clusterTime: { clusterTime: Timestamp(1579010568, 1), signature:
{ hash: BinData(0, 2F281F7B9881E802501648F77CC4113E4B119167), keyId: 6749132984986632193 } }, $db: "test" }
    at Connection.<anonymous> (C:\wamp64\www\bsmart\PRAMS\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:443:61)
    at Connection.emit (events.js:210:5)
    at processMessage (C:\wamp64\www\bsmart\PRAMS\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:364:10)
    at TLSSocket.<anonymous> (C:\wamp64\www\bsmart\PRAMS\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:533:15)
    at TLSSocket.emit (events.js:210:5)
    at addChunk (_stream_readable.js:309:12)
    at readableAddChunk (_stream_readable.js:290:11)
  

Open in new window

0
Here's my code:

module.exports = (req, res, next) => {
	const authHeader = req.get('Authorization');
	if(!authHeader) {
		const error = new Error('Not Even Working');
		error.statusCode = 401;
		throw error;
	} else {
		//const token = authHeader.split(' ')[1];
		let decodedToken;
		try {
			decodedToken = jwt.verify(token, 'secret');
		} catch (err) {
			err.statusCode = 500;
			throw err;
		}
		if(!decodedToken) {
			const error = new Error('Not Authenticated');
			error.statuscode = 401;
			throw error;
		}
		req.userID = decodedToken.userId;
		next();
	}
};

Open in new window


I'm going through some of my back end and forcibly making things go south and I've discovered that I like being able to see things like "Not Even Working," in addition to my status code.

Now, all cards on the table, the above code is coming from a tutorial, so I'm not all that, but I still want to ask this question:

In the first block, I establish an "error" const and I throw my error which has some verbiage that helps me know exactly where things went south.

The next block I've got a try / catch.

Now, when I think "try / catch," I'm thinking this is just a different kind of IF clause, yes? Perhaps the "try" presupposes the fact that we're actually going to fire some kind of function as opposed to just testing the presence of a variable?

But I want to have something even in the context of a "try / catch," where I can specify a "new Error," so I can write some custom verbiage to my console.

So, why am I using "try / catch?" I understand the utility of "throw," because that prevents the code from moving forward.

But why "try / catch? as opposed to a regular IF and can I incorporate some custom verbiage in the midst of that "try / catch?"

Thanks!
0
New to Node.js, but getting more comfortable with it every day.

Ah, but wait...

We got a note today from the boss that we need to head out to a repository, download the codebase and start looking it over.

So I clone the repository and this is what I have on my local box:

prams
I'm assuming that "PRAMS" is kind of like a suitcase for a Node.js application based on what I see here: https://www.npmjs.com/package/pram

...but I would like some confirmation on that.

Next, I follow my nose and I copy and paste the contents of the PRAMS directory to that place where I can fire it up on my local box.

But what port is it going to be firing on?

I run npm index.us and I get this:

Usage: npm <command>

where <command> is one of:
    access, adduser, audit, bin, bugs, c, cache, ci, cit,
    clean-install, clean-install-test, completion, config,
    create, ddp, dedupe, deprecate, dist-tag, docs, doctor,
    edit, explore, get, help, help-search, hook, i, init,
    install, install-ci-test, install-test, it, link, list, ln,
    login, logout, ls, org, outdated, owner, pack, ping, prefix,
    profile, prune, publish, rb, rebuild, repo, restart, root,
    run, run-script, s, se, search, set, shrinkwrap, star,
    stars, start, stop, t, team, test, token, tst, un,
    uninstall, unpublish, unstar, up, update, v, version, view,
    whoami

npm <command> -h  quick help on <command>
npm -l            display full usage info
npm help <term>   

Open in new window

0
Hi Experts

Could you point why an Excell file read at browser (js) is obtained at PHP code as a tmp file?

Accordingly with:
img001
The JS code called (that produces the console showed above):

 
User.prototype.subirLote = function() {
 // Called to upload the file
   console.log('XXXX');
  $("#arquivoLote").trigger("click");
  
  arquivo = $("#arquivoLote").val();
  
// The name is empty
  console.log('Y ' + arquivo);

};

Open in new window


When this PHP code is called:
<? 
//------------------------------------------------------------
    public function subirLote(Request $request){
//------------------------------------------------------------  
      
      $arquivo=$request->file('arquivoLote');
	  
	  
*--- AT THIS POINT THE FILE IS RECEIVED AS: C:\xampp\tmp\php6669.tmp (OR SOMETHING LIKE)
file_put_contents('debug.log', 'Arquivo = '. $arquivo.PHP_EOL , FILE_APPEND);
*-----------------------------------------------------------------------------

      Config::set('excel.import.heading', 'slugged_with_count');
      Config::set('excel.import.startRow', 1);

      try{

        $arquivoUrl = AzureStorage::saveFile($arquivo,'arquivos');
    
        $planilha = Excel::selectSheets('Participantes')->load($arquivo)->toArray();
      
        $validacao = $this->validarArquivo($planilha);
        

        if(!$validacao["valido"])
		{  
   
          return response()->json(new Resultado(false,"",$validacao));
        }
        
        

Open in new window

0
I have a panel that I am making draggable with the following code:
function dragElement(elmnt) {
    var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    var mouseClick = mousedown;
    if (document.getElementById(elmnt.id + "header")) {
        /* if present, the header is where you move the DIV from:*/
        document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
        //For mobile devices
        document.getElementById(elmnt.id + "header").ontouchstart = dragMouseDown;
    } else {
        /* otherwise, move the DIV from anywhere inside the DIV:*/
        elmnt.onmousedown = dragMouseDown;
        //For mobile devices
        elmnt.ontouchstart = dragMouseDown;

    }

    function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // get the mouse cursor position at startup:
        //pos3 = e.clientX;
        //pos4 = e.clientY;
        // get the mouse cursor position at startup:
        pos3 = e.clientX || e.touches[0].clientX;
        pos4 = e.clientY || e.touches[0].clientY;
        document.onmouseup = closeDragElement;
        //For mobile devices
        document.ontouchend = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
        //For mobile devices
        document.ontouchmove = elementDrag;
    }

    function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();
        // calculate the new cursor position:
    

Open in new window

0
Hi JavaScript Experts,

I’m trialing some code to make it so HTML <select multiple> controls don’t need Ctrl to be held down while clicking, to select/deselect options without deselecting all other selected options.  I picked up this solution from the JSFiddle in the accepted solution from here.

I don’t know much JavaScript, but I guessed how to change that JSFiddle so it respected disabled options, by simply adding a condition, and here’s the resulting JSFiddle including that change.

Now I’m wanting to see if I could have a plain JavaScript (i.e. without jQuery) version of that, so I can compare performance, because I don’t (yet) need jQuery for anything else in my Perl web application and if a plain JavaScript version works out to be lighter, I’ll use it, because page load speed is important for this light application.  I know jQuery caches, but it will reload during refreshes.  So could someone please convert it for me?  If it's going to be too long/hard to convert while retaining a good level of browser compatibility, let me know.

Also, the code seems to work on Firefox, Chrome, Opera, Edge, but not IE11 for some reason (i.e. Ctrl click is still required).  Any ideas why or how to fix that?  If not, I’m not too worried, because I hear IE’s days are numbered.

Here's the code for your convenience:

Open in new window

0
Hello Experts,

I have a textbox(input) when user enter accept only numbers(digits only) and it should be 10. Once entered we need for format like (123)456-7890. I tried below but not working as expected.
CSHTML
 <input type="text" id="PhoneNumber" name="PhoneNumber" value="" class="form-control" autofocus="autofocus" maxlength="11">
                                <span class="bar" id="ErrMsg" ></span>
                                <label for="PhoneNumber">Phone</label>

Open in new window


JS
$("#PhoneNumber").keypress(function (e) {
    //if the letter is not digit then display error and don't type anything
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#ErrMsg").html("Digits Only").show();
        return false;
    }
});

$("#PhoneNumber").blur(function (e) {
    phone = $(this).val();
    if (phone.length != 10) {
        $("#ErrMsg").html("Phone number must be 10 digits.").show().fadeOut("slow");
        return false;
    }
    else
        $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
});

Open in new window


I have couple of issues with the above code, first I did Maxlength 11 then only it's accepting 10 digits and also I get format like this (123)456-0 (since my maxlenght was 11). After changing Maxlength to 14, I still get same issue. Please suggest how can I solve this.

Thanks,
ASPDEV
0
Hi I m populating data like below in tabular foarmat . my requirement is like while submiting ajax call before that
each row which is cheked having 3 date field need to validate Q Date should greater then P Date ,
B Date sholud be greater then Q Date and P Date. pelase help me out with some code snippet.


<table align=center>

<tr>			<th>Check/UnCheck</th>
                <th>MYear</th>
                <th>P Date</th>
                <th>Q Date</th>
                <th>B Date</th>
</tr>
<%for(int i=0 ; i<mVector.size();i++)
{
	
%>
 <tr>
<td align="top">
<INPUT type="checkbox" class="chkValues" id="ckbCheckAll" name="chkBox" type="checkbox" data-row="row<%=i%>" value="" size="50">
</td>
<td align="left">
<input class="inputText row<%=i%>" type="text" name="mYear" id="mYear"  value="<%=mVector.elementAt(i)%>">
</td>

				<td>
		            <input class="date row<%=i%>" id="pDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(0)==null?"":oldValues.elementAt(0))%>" />
				</td>
				<td>
		            <input class="date row<%=i%>" id="qDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(1)==null?"":oldValues.elementAt(1))%>" />
				</td>
				<td>
		            <input class="date row<%=i%>" id="bDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(2)==null?"":oldValues.elementAt(2))%>" />
				</td>

</tr> 
<%}%>

</table>

Open in new window



ajax call is like below


$(document).ready(function() {

	$(".date").datepicker({dateFormat:'dd/mm/yy'});
	

	$('.chkValues').on('click', function() {

		//get values of dates
		var array = [];
		$row = $(this).data('row'); //row1, row2, row3 etc
		$('input.' + $row).each(function() {
			array.push($(this).val());
		});
		$('#btnSubmit').click(function(evt) {
    	evt.preventDefault();
    	$.ajax({
            type: "POST",
            url: "Test.jsp",
            data: {array : array},
            success: function(responseFromServer) {
            	 $.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
                    $('#content').html(resultMessageKey);
                });
    	    	//getClearDateValues();
    		
            },
            error: function() {
                alert(" Ajax call Failed to Update Values  into Database ");
            }
        }); 
		});

	});

});

Open in new window

0
Hi In below function i m calling one validate function save()
if save() execute and give all values validated then ajax call go
other wise ajax call don't go . in below code save function is working
perfectly but when it gives no validation error ajax call is not going.
please help me out to recify this.


$(document).ready(function() {
	$("#save_data").click(function(evt) {
		evt.preventDefault();
		alert("succeess");
		if (save()){
			$.ajax({
				url: "Test.jsp",
				type: "post",
				data: {
				pS:$('#pS').val(),
				psT:$('#psT').val(),
				pC:$('#pC').val(),
				mY:$('#mY').val(),
				pDate:$('#pDate').val(),
				pdDate:$('#pdDate').val(),
				bDate:$('#bDate').val()},
				success: function(responseFromServer) {
	            	$.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
	                    $('#content').html(resultMessageKey);
	                });
	                //$('#content').html("Date Confguration Saved");
	    	    	//getClearDateValues();
	    		
	            },
	            error: function() {
	                alert(" Ajax call Failed to Update Values into Database");
	            }
			});
		}
	});
});

Open in new window

0
Hi i am sending ajax request to java servlet on success ia m prining the response to servlet and sending back as ajax response
but after executing it gives error like below -

jquery-1.9.1.min.js:3 Uncaught TypeError: Cannot use 'in' operator to search for '72' in


{"Request Processed":"Request Processed"}
0
Hi Experts,

How can I use Viewport sizing in WP, so there's only one design for desktop, mobile and tablet?

I know that this is an outdated method, but "the customer is always right."

My favorite theme is Appointment Pro that I use at www.aces-project.com, but how would I approach it with this or any other theme? The site will be similar to http://www.povardarska-eparhija.org.mk/pe/

Thank you
0
Hi all,

I am building a table that automatically shows who is the person that is in charge of cleaning the kitchen in plain Javascript.

This is what I have so far:
<style>
th, td {
  padding: 15px;
  text-align: left;
}

tr:hover {background-color: #f5f5f5;}

table {
  width: 100%;
}
</style>

<div id="cleaningTableDiv">
</div>


<script>

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

function plainTableCreate(currentWeekNumber) {
    // Table variables
    var teamMembers = ["Flatmate1", "Flatmate2", "Flatmate3", "Flatmate4", "Flatmate5", "Flatmate6"];
    var rowNumber = 7;
    var colNumber = teamMembers.length * 2 + 1;
    var headings = ["Week number"]
    for (var i = 0; i < colNumber - 1; i++) {
        headings.push(currentWeekNumber + i);
    }

    // Creating table
    var body = document.getElementById('cleaningTableDiv');
    var tbl = document.createElement('table');
    tbl.setAttribute("id", "cleaningTable");
    var tbdy = document.createElement('tbody');
    for (var i = 0; i < rowNumber; i++) {
        var tr = document.createElement('tr');
        for (var j = 0; j < colNumber; j++) {
            var td = document.createElement('td');
            td.appendChild(document.createTextNode(""));
            tr.appendChild(td);
        }
        tbdy.appendChild(tr);
    }
    tbl.appendChild(tbdy);
    

Open in new window

0

JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.