I'd like to build a string based on values defined in an html form only if they have been populated. I've successfully parsed the form fields and dropdown with a for loop ($.each()) but my ultimate goal is to dynamically build a string with the results. The string is being used to create a REST query, this is currently the only way to search based on our technologies. Does anyone have a recommended solution?
thx in advance
sample html element:
<input data-param=" prefix like '%" data-name="prefix" class="prefix uno" type="text" placeholder="pre">
working btn click event loop to capture filled in form fields:
var children = $(this).parent().children('.uno');
$.each(children, function(i, val){
if($(val).val() !== ''){
console.log($(val).data('name') + " "+ $(val).data('param') + " " + $(val).val());
}
});
goal:
var newString = field1.param + field1.val + '% ' + field2.param + field2.val + '% ';
translated:
var newString = prefix like '%01%' and name like '%tree%';
Thanks David Fregoli for the jquery serialize reference, that was close, but the solution ended up being to place the strings into a single array, change it toString(), and remove the ',' from the new string.
code:
var samp = [],
thisVal = $(this).parent().children('.uno');
$.each(thisVal, function(i, val){
if($(val).val() !== ''){
samp.push(
$(val).data('param'),
$(val).val(),
$(val).data('close')
);
}
});
itQuery.where = samp.toString().replace( /,/g , '');
result search string:
"number like '%08%' and field = 34"
Related
I'm using Jquery to find the users email in my site, but I don't know how can I find a email for users with the same name.
Using this code, my variable return just one value for string.
var mail = $("#dat").contents().find("td:contains('" + name + "')" ).siblings("td").eq(1).text();
How can I get all strings that match in this find event?
Thanks!
EDIT: My code don't have any HTML markup for data, I'm using Google Spreadsheet to get the values.
Imagine there is one table with:
<tr><td>Name 1</td><td>mail1</td></tr>
<tr><td>Name 2</td><td>mail2</td></tr>
<tr><td>Name 1</td><td>mail3</td></tr>
If I use find containing "Name 1", my variable should return mail1, mail3.
To get the second column of all matching rows, use nth-child.
To get all values in an array, you can use map() and get()
var name = 'Name 1';
var mail = $("#dat").contents()
.find("td:contains('" + name + "')" )
.siblings("td:nth-child(2)")
.map(function() {
return $(this).text();
}).get()
document.body.innerHTML = '<pre>' + JSON.stringify(mail, 0, 4) + '</pre>';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="dat">
<tr><td>Name 1</td><td>mail1</td></tr>
<tr><td>Name 2</td><td>mail2</td></tr>
<tr><td>Name 1</td><td>mail3</td></tr>
</table>
The query for find could be more specific as well, that way using siblings wouldn't be neccessary
var mail = $("#dat").contents()
.find("tr:has(td:contains('" + name + "')) td:nth-child(2)" )
.map(function() {
return $(this).text();
}).get()
You should change you code a little, to:
mail = $("#dat").contents().find("td:contains('" + name + "')" ).next().text();
Check demo - Fiddle
I'm creating a small web-app for my girlfriend and I that will allow us to keep track of the movies we want to watch together. To simplify the process of adding a movie to the list, I'm trying to use TheMovieDatabase.org's API (supports JSON only) to allow us to search for a movie by title, let the database load a few results, and then we can choose to just add a movie from the database or create our own entry if no results were found.
I'm using jQuery to handle everything and, having never used JSON before, am stuck. I wrote a short bit of code to get the JSON based on my search query, and am now trying to populate a <ul> with the results. Here's what I have.
var TMDbAPI = "https://api.themoviedb.org/3/search/movie";
var moviequery = $("#search").val();
var api_key = "baab01130a70a05989eff64f0e684599";
$ul = $('ul');
$.getJSON( TMDbAPI,
{
query: moviequery,
api_key: api_key
},
function(data){
$.each(data, function(k,v) {
$ul.append("<li>" + k + ": " + v + "</li>");
}
);
});
The JSON file is structured as
{
"page":1,
"results":[
{
"adult":false,
"backdrop_path":"/hNFMawyNDWZKKHU4GYCBz1krsRM.jpg",
"id":550,
"original_title":"Fight Club",
"release_date":"1999-10-14",
"poster_path":"/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg",
"popularity":13.3095569670529,
"title":"Fight Club",
"vote_average":7.7,
"vote_count":2927
}, ...
"total_pages":1,
"total_results":10
}
but all I'm getting is
page: 1
results: [object Object], ...
total_pages: 1
total_results: 10
I've searched quite extensively on the Internet for a solution, but with the little knowledge I have of JSON I wasn't able to learn much from the various examples and answers I found scattered about. What do?
It looks like what you'd like to do is write out some properties of each movie in the list. This means you want to loop over the list in data.results, like this:
// Visit each result from the "results" array
$.each(
data.results,
function (i, movie) {
var $li = $('<li></li>');
$li.text(movie.title);
$ul.append($li);
}
);
This will make a list of movie titles. You can access other properties of movie inside the each function if you want to show more elaborate information.
I added the title to the li using $li.text rather than simply doing $('<li>' + movie.title + '</li>') since this will avoid problems if any of the movie titles happen to contain < symbols, which could then get understood as HTML tags and create some funny rendering. Although it's unlikely that a movie title would contain that symbol, this simple extra step makes your code more robust and so it's a good habit to keep.
You need to traverse the results object. In the $.each function change data for data.results
You can use a simple for loop to iterate over the list/array. in the example below i am appending a list item containing the value of the key results[i].title. you can append the values of as many valid keys as you would like to the div.
var TMDbAPI = "https://api.themoviedb.org/3/search/movie";
var moviequery = $("#search").val();
var api_key = "baab01130a70a05989eff64f0e684599";
$ul = $('ul');
$.getJSON( TMDbAPI,
{query: moviequery,api_key: api_key},function(data){
var results = data.results;//cast the data.results object to a variable
//iterate over results printing the title and any other values you would like.
for(var i = 0; i < results.length; i++){
$ul.append("<li>"+ results[i].title +"</li>");
}
});
html
<input id="search" type="text" placeholder="query" />
<input id="submit" type="submit" value="search" />
js
$(function () {
$("#submit").on("click", function (e) {
var TMDbAPI = "https://api.themoviedb.org/3/search/movie";
var moviequery = $("#search").val();
var api_key = "baab01130a70a05989eff64f0e684599";
$.getJSON(TMDbAPI, {
query: moviequery,
api_key: api_key
},
function (data) {
$("ul").remove();
var ul = $("<ul>");
$(ul).append("<li><i>total pages: <i>"
+ data.total_pages + "\n"
+ "<i>current page: </i>"
+ data.page
+ "</li>");
$.each(data.results, function (k, v) {
$(ul).append("<li><i>title: </i>"
+ v.original_title + "\n"
+ "<i>release date: </i>" + v.release_date + "\n"
+ "<i>id: </i>" + v.id + "\n"
+ "<i>poster: </i>"
+ v.poster_path
+ "</li>");
});
$("body").append($(ul))
});
});
});
jsfiddle http://jsfiddle.net/guest271314/sLSHP/
I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);
We are generating a dynamic url from the data entered into a form. We are currently able to append this dynamic form data into the url, but need to include static data at the END of the dynamic data.
Here is the last part of the jQuery that appends the data:
var inputs = $('#form1').find('input[type=text]').not('#url');
var str = "http://yoururlhere.com/dispatch.aspx?"
var str2 = "&promoid=5030385&option1=999"
inputs.each(
function (i, item) {
str += encodeURIComponent(item.name) +
"=" +
encodeURIComponent(item.value) +
"&";
});
$('http://yoururlhere.com/dispatch.aspx?').val(str+str2);
});
The end result from what we get:
http://yoururlhere.com/dispatch.aspx?address=1290 atlantis ave&zip=80026
And this is what we are trying to achieve:
http://yoururlhere.com/dispatch.aspx?address=1290 atlantis ave&zip=80026&promoid=5030385&option1=999
The last bit (promoid=5030385&option1=999) will be constant for every form entry.
*EDIT*
I solved it by putting the static data as a hidden field in the html:
<input type="hidden" name="promoid" value="5030385" id="promoid"/>
Thank you all for your comments and help!
try this
var inputs = $('#form1').find('input[type=text]').not('#url');
var str = "http://yoururlhere.com/dispatch.aspx?"
var str2 = "&promoid=5030385&option1=999"
inputs.each(function (i, item) {
str += encodeURIComponent(item.name) + "=" + encodeURIComponent(item.value) + "&";
});
str = str+str2;
});
I am working on a simple form demo and i would like the input to display in a below the form. Currently i have it populating in the console. How do i may it display in the div when i click the submit button?
My code:
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$('#firstName').val();
$('#lastName').val();
$('#phoneNumber').val();
$('#address').val();
console.log($('#firstName').val());
console.log($('#lastName').val());
console.log($('#phoneNumber').val());
console.log($('#address').val());
});
});
Well, you're currently not putting the values anywhere but into the console.log.
I would expect to see something like (let's call your div you want the values to go to, "output"):
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
// Borrowing from another response, this is better
// Putting these in variables protects you from
// 1) accidentally modifying your form values
// 2) invalid input, if you add some basic checks, like
// testing to see if the length is > 0, doesn't contain
// bad characters, etc.
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
phone = $('#phoneNumber').val(),
address = $('#address').val();
// get a reference to the div you want to populate
var $out = $("#output");
// This is a better way of dealing with this
// because every call to .append() forces DOM
// reparsing, and if you do this too often, it can cause
// browser slowness. Better to put together one string
// and add it all at once.
$out.html("<p>" + firstName + "</p>" +
"<p>" + $('#lastName').val() + "</p>" +
"<p>" + $('#phoneNumber').val() + "</p>" +
"<p>" + $('#address').val() + "</p>");
});
});
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$(this).after('<div>First name: '+$('#firstName').val()+'<br>'+
'Last name: '+$('#lastName').val()+
' .... ');
});
});
First of all, the four lines where you read the .val() but don't do anything with it are essentially wasted cycles, you probably meant to store them in variables:
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
var phoneNumber = $('#phoneNumber').val();
var address = $('#address').val();
To show them in some other element, use the setter version of .val() for input types, or .text() if it's a display type (div, span, etc):
$('#someOtherElement').text(firstName + '\n' +
lastName + '\n'
phoneNumber + '\n'
address);
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
//$('#firstName').val();
//$('#lastName').val();
//$('#phoneNumber').val();
//$('#address').val();
var htmlContent = $('#firstName').val() + '<br />' + $('#lastName').val() + '<br />' + $('#phoneNumber').val() + '<br />' + $('#address').val();
$('#ID_OF_YOUR_DIV_HERE').html(htmlContent);
});
});
Maybe this is what you're after??
You can add it to a div you want with .append(), for example
$("#divYouWantToAddTo").append($('#firstName'));
I don't know where to start... What is all that $('#....').val() in the middle there, wasting time only to throw away the result..?
What is wrong with document.getElementById('...').value instead of wasting time creating an entire jQuery object just to access something trivial?
Adding text to a node is as simple as container.appendChild(document.createTextNode(sometext)); - and if you want to have newlines between them you can also do container.appendChild(document.createElement('br'));.
There is no need for jQuery here at all...