I have a jQuery function that is executed by two different buttons.
$("#btnSearch, #btnDirectorSearch").click(function () {
Part of the html that this function builds depends on which button was hit. I am using data- attributes to store my variables like this:
var div = $(this).data("str");
And the html string I am building depends on what value the variable "div" is. Is there a way to do an inline if/else statement in jQuery?
if div = "choice1" {
html += '<tr data-str = "str1" data-dataItem = "dataItem1" data-result-title = "' + name + '" data-result-id="' + sel + '">';
} else {
html += '<tr data-str = "str2" data-dataItem = "dataItem2" data-result-title = "' + name + '" data-result-id="' + sel + '">';
}
That seems cumbersome and I'm hoping there is a better jQuery way of doing this.
Thanks!
you have a syntax error
if div = "choice1"
should be
if (div == "choice1")
Anyway, the pattern you're looking for is:
div == "choice1" ? <code for true> : <code for false>
you can use condition ? code when true: code when false
but i would suggest you to stick with curley braces only, as it looks better and easier to debug.
one more thing , do it as below
if(div==="choice1"){
}
else{
}
use ===
Since it's only the number that changes in the output, you could do this:
var num = div == "choice1" ? 1 : 2;
html += '<tr data-str="str'+num+'" data-dataItem="dataItem'+num+'" data-result-title="'+name+'" data-result-id="' + sel + '">';
If your choices are limited, you could add a small lookup array:
var choices = {
choice1: {
str: "str1",
data: "dataItem1"
},
choice2: { ... }
};
html += '<tr data-str="' + choices[div].str
+ '" data-dataItem="' + choices[div].data
+ '" data-result-title="' + name + ... etc;
Related
I am trying to append some data in html table using jquery that is working fine but when the data is null or empty i have to append another div to that html table.
Am trying like this
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
but it is not working please help me how to fix this...
Never understand why somebody use this
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
Instead of this:
//class declaration
function YourTableCell(name, value) {
this.input = document.createElement('input');
this.input.value = value;
this.input.name = name;
this.label = document.createElement('label');
this.label.text = 'My Label';
this.container = document.createElement('td');
this.container.appendChild(this.input);
this.container.appendChild(this.label);
}
//application buisness logic
if(data.d[i].one != ''){
var cell = new YourTableCell(data.d[i].name, data.d[i].value);
$("#table").append(cell.container);
} else {
$("#table").append(document.createElement('div'));
}
Using this approach you can incapsulate table cell building inside of your class and make your code much more readable and reusable. Also, as I see now, you are trying to append td inside of something with id #table, and look like it is incorrect, because you should append td inside of tr.
Also, using this you can get references to all objects such as inputs and avoid of $('input, select, textarea') selectors.
You could use something like this,
var html = '<div></div>';
if(data.d[i].one) {
html = '<td id="divs"><input id="' + data.d[i].one + '" type="checkbox" class="cbCheck"><label for="' + data.d[i].one + '"></label></td>';
}
("#table").append(html);
You could use :
if( data.d ){
//Your code
}
That will check if data.d is NULL or empty string "".
If you want to check in every iteration use the index i :
if( data.d[i] ){
//Your code
}
Hope this helps.
Take a look to https://stackoverflow.com/a/5515349/4281779.
I'm using
http://davidstutz.github.io/bootstrap-multiselect/ for creating bootstrap multiselect controls in my webpage.
The below fiddle link with static data is what I want to achieve using dynamic data:
https://jsfiddle.net/DROCKS/mrmLrsad/4/
//please refer the fiddle
The search option works fine in case the values of the select box are static, but if they are dynamically created, the multiselect gets created. However the search filter is not working in this case. However the my code is similar to the fiddle below, the only difference being that the search filter part doesn't work in my actual code, but works in this fiddle.
fiddle link with dynamic data.
https://jsfiddle.net/DROCKS/mrmLrsad/5/
//please refer the fiddle
This is my code.
HTML code
<select id="lstFieldList" ></select>
jQuery code [Updated]:
function uncheckFields(field_id)
{
$('#' + field_id).multiselect('deselectAll', true);
}
//json_obj is the value from the fiddle.
createMultiSelectBox(json_obj);
//this function creates the multiselect
function createMultiSelectBox(json_obj)
{
var element_String = "";
var default_ele_set = 0;
var def_element_first = "1"; //if the first Y flag should be considered
var def_element_last = "n"; //if the last Y flag should be considered
var def_element = def_element_first; //change the value here to toggle between default selection
var tmp = [];
for (var key in json_obj)
{
var val = json_obj[key];
//alert("Key: " + key);
var chk_box_ctr = 0;
var element;
for(var child_key in val)
{
//alert("key: " + child_key + "\nvalue: " + val[child_key]);
var default_value = child_key.split(",")[7];
//alert("default_value: " + default_value);
if(!chk_box_ctr)
{
g_max_PageSize = child_key.split(",")[8];
//alert("g_max_PageSize: " + g_max_PageSize);
}
if(def_element == def_element_first)
{
if(default_value == "Y" && !default_ele_set)
{
//element_String += '<option value="' + child_key + '" selected="selected">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
else
{
//element_String += '<option value="' + child_key + '">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
}
else
{
if(default_value == "Y")
{
//element_String += '<option value="' + child_key + '" selected="selected">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
else
{
//element_String += '<option value="' + child_key + '">' + val[child_key] + '</option>';
element = {"label": val[child_key],"value":child_key};
}
}
tmp.push(element);
}
if(def_element == def_element_last)
{
uncheckFields('lstFieldList');
}
}
//$('#lstFieldList').append(element_String);
//$('#lstFieldList').multiselect('rebuild');
$("#lstFieldList").multiselect('dataprovider', tmp);
$('#lstFieldList').multiselect({
maxHeight: 200,
buttonWidth:"100%",
enableFiltering:true,
enableCaseInsensitiveFiltering:true,
/*maxHeight: 200,
enableCaseInsensitiveFiltering: true,
//enableFiltering: true,
onChange: function(option, checked, select) {
alert('Changed option ' + $(option).val() + '.' + "\nchecked: " + checked + "\nselect: " + select);
if(checked)
{
//uncheckFields('lstFieldList');
}
else
{
uncheckFields('lstFieldList');
}
}*/
});
var elem = $('#lstFieldList').next();
elem.attr('class',(elem.attr('class') + ' open'));
}
What could be the problem? because the same code is present in both the files.
Any help would be appreciated.
Thanks in advance.
create an array var tmp = [];
create a json like this while looping for option
element = {"label": this.Name,"value":this.id};
and push each element to tmp
tmp.push(element);
and pass this tmp array to multi select
$("#lstFieldList").multiselect('dataprovider', tmp);
and add multiselect to dropdown by
$("#lstFieldList").multiselect({
maxHeight: 260,
buttonWidth:"100%",
enableFiltering:true,
enableCaseInsensitiveFiltering:true,
});
I actually found out what was causing the unusual behavior in the code related to the bootstrap multiselect plugin. The code given to me by Anoop was right, I also tried various different codes related to the same plugin in the past months, but I later drop the idea to use the plugin.
Then lately last week while reworking on the same code, I identified that I had included some js script files in my html page. So I tried commenting out each include statement for the files in my html to identify which one was causing the issue. So on doing so I reached at a particular js file.
Once the file was identified, I just needed to find out which function was causing the problem to the suggestion logic of the plugin. So to identify this, I kept on commenting/removing the functions till I arrived to the function that caused the issue. There was a code related to window.setTimeout. It was due to this function that the existing suggestion logic was not working as the code was coming into this block. So I later added some flagging logic to avoid running this function in my case.
Thanks a lot all for your inputs.....
My question is this, if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Not sure if I can do this, but I'm hoping I can. What I have is a bit of javascript code that is taking data from an xml document. I have a list of 500+ cards that I have parsed through and stored by categories that are used often. Here are the relevant functions as they apply to my question.
var Card = function Card(cardName, subTitle, set, number, rarity, promo, node)
{
this.cardName = cardName;
this.subTitle = subTitle;
this.set = set;
this.number = number;
this.rarity = rarity;
this.promo = promo;
this.node = node;
}
Where node is the position within the list of cards, and due to the formatting of the document which I started with contains each card alphabetically by name, rather than numbered logically within sets.
Card.prototype.toLink = function()
{
var txt = "";
this.number;
if (this.promo == 'false')
{
var image = this.set.replace(/ /g, "_") + '/' + this.number;
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + "')>";
txt += this.toString() + "</" + "a>";
}
else
{
var image = this.set.replace(/ /g, "_") + '/' + this.rarity + this.number;
var txt = "";
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ')>";
txt += this.toString() + "</a>";
}
return txt;
}
Here is what I am using to populate a list of cards, with names that upon hovering over will display a card image.
function populateList () {
for (i = 0; i<cards.length; i++)
document.getElementById('myList').innerHTML += '<li>'+cards[i].toLink()+</li>;
}
What I am trying to do is retrieve the id of the element with the onmouseover event so that I can retrieve everything that is not being saved to a value.
I realized I can pass the id as part of the changeImage function as a temporary workaround, though it involves rewriting my toLink function and my changeImage function to include a second argument. As a married man, I've enough arguments already and could do with one less per card.
In summary, and I suppose all I needed to ask was this, but is there a way using only javascript and html to retrieve the id of an element, onmouseover, so that I may use it in a function. If you've gotten through my wall of text and code I thank you in advance and would appreciate any insights into my problem.
if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Yes, if you can change the link (and it looks like you can):
<a id='1' onmouseover="changeImage('setname/setnumber', this)">Cardname</a>
Note the new argument this. Within changeImage, you'd get the id like this:
function changeImage(foo, element) {
var id = element.id;
// ...
}
Looking at your code, you'd update this line of toLink:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', this)>";
Of course, you could also just put the id in directly:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', " + this.node + ")>";
And then changeImage would be:
function changeImage(foo, id) {
// ...
}
I didn't use quotes around it, as these IDs look like numbers. But if it's not reliably a number, use quotes:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', '" + this.node + "')>";
I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here
I write a form that inserts some xml tags into textarea. I use this function:
(function ($) {
addCustomTag = function (name, param, value) {
var code = "<" + name + " " + param + "=\"" + value + "\">\n</" + name + ">";
document.getElementById("codeArea").value += code;
};
})(jQuery);
How can I make that some other function will insert subtags into tags that were created before?
XML code will never be used on server. All I need is to insert tex in specific line which is depends on what was on this line before not cutting it. Something like this:
addCustomSubtag = function(name,param,value,parent) {
document.getElementById("codeArea").selectionStart = document.getElementById("codeArea").value - parent.length;
var code = "<" + name + " " + param + "=\"" + value + "\">\n</" + name + ">";
document.getElementById("codeArea").value += code;
};
Javascript isn't necessary. It also can be written on jQuery.
Thanks.
You can any of these jQuery functions
http://api.jquery.com/append/
http://api.jquery.com/appendTo/
http://api.jquery.com/prepend/
Update:
Actually we can use jQuery DOM manipulation methods to manipulate XML also.
var xml = "<main/>";
alert(xml); // <main/>
var $xml = $(xml).append($("<sub1/>"));
alert($xml.html()); // <sub1></sub1>
$xml.find("sub1").append($("<sub2/>"));
alert($xml.html()); // <sub1><sub2></sub2></sub1>
alert($xml.get(0).outerHTML); // <main><sub1><sub2></sub2></sub1></main>