javascript variables in jquery selectors not working - javascript

I am trying to bring the variable name inside the selectors, but its not working,
here is the code, from where I have taken the example
How to use javascript variables in jquery selectors
and here is my code
$(document).ready(function() {
//var detail = sample.one;
var detail = sample;
$('#' + detail).click(function() {
});
});

you need to put the value between " because you want to store a string in your variable.
var detail = "sample"

Try this:
$(document).ready(function() {
var detail = 'sample';
$('#' + detail).click(function() {
});
});

$(document).ready(function() {
//var detail = sample.one;
var detail = 'sample';
$('#' + detail).click(function() {
});
});
<input type="button" id="sample" />
This is working.
sample is a string so use "

create a variable with string value for example
var detail = 'sample';

Related

Reusing Javascript code without repasting it again and again

I have the below code, which looks for the text "UID" and changes it to "UID *"
On my page, there are other terms such as "description", "score" and so on. I would also like to append * to these as well - is there a tidy way to get the below code to edit those as well? Only way I know is to repeat this code block again and again?
<script type="text/javascript">
//Mark UID as Mandatory
var CFN = "UID";
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(CFN, 'UID *'));
});
}
</script>
EDIT. I tried the below reply, but this didn't work for me, I have got this code now, but again, doesn't seem to work (its trying to add a * onto "UID" and "Description" where found using a multi variable;
<script type="text/javascript">
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.append(MandatoryCFs, ' *'));
});
}
</script>
Replace multiple strings by using list of| Regex
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(new RegExp(MandatoryCFs.join('|'),'g'), '$& *'));
});
}
or like this if you don't need to the replaced strings to be dynamic:
text.replace(/UID|Description/g, '$& *')

How to parse XML in JavaScript

https://jsfiddle.net/recklesswish/6yw1tdwh/5/ The following link has the JSON and i have converted this particular JSON in XML. Now the issue is I am not getting that how to parse it using javascript.
Here is the code of xml, JSON resp.
XML
var carsData = "<cars>
"<Honda>"
"<model>Figo</model>"
"</Honda>"
"<Honda>"
"<model>City</model>"
"</Honda>"
"<Audi>"
"<model>A6</model>"
"</Audi>"
"<Audi>"
"<model>A8</model>"
"</Audi>"
"</cars>"
JSON
var carsData = '{"cars":{"Honda":[{"model":"Figo"},{"model":"City"}],"Audi":[{"model":"A6"},{"model":"A8"}]}}';
$('#newCollection').on('click', function() {
$(this).empty();
var data = JSON.parse(carsData);
$(this).append('New Collection<ul></ul>');
for (var make in data.cars) {
for (var i = 0; i < data.cars[make].length; i++) {
var model = data.cars[make][i].model;
$(this).find('ul').append('<li>' + make + ' - ' + model + '</li>')
}
}
});
With HTML
<ul>
<li id="newCollection">New Collection</li>
</ul>
First of all make your xml look like this in javascript -
var carsData = "<cars><Honda><model>Figo</model></Honda><Honda><model>City</model>
</Honda><Audi><model>A6</model></Audi><Audi><model>A8</model></Audi></cars>"
And your JS code would look like this -
$('#newCollection').on('click', function() {
$(carsData).find("Honda").each(function() {
var model = $(this).find("model").text();
console.log("model: " + model );
});
});
newCollection is the id of your button. This will print model as below-
model: Figo
model: City
I would suggest you to go through basics first rather than trying to jump into coding directly. Clear basics will make you a good coder in long run :)
I see. Use below code to achieve what you want -
<body>
<h1>Hello</h1>
<button type="button" id="newCollection">Click Me!</button>
<ul id="myul"></ul>
</body>
And your JS code should be -
$('#newCollection').on('click', function() {
var data = $($.parseXML(carsData));
data.find('cars').children().each(function() {
var make = $(this).find("model").text();
$('#myul').append('<li>'+make+'</li>');
});
});

Passing a jquery variable

i'm having trouble with the following jquery code
$this->registerJs(
'jQuery(document).ready(function($){
$(".member").on("change",function(){
var id = $(this).attr("id");
// alert(id);
var n = $(this).val();
// alert(n);
$.post("'.\Yii::$app->getUrlManager()->createUrl(['death/stl_set_relation','id'=>'+id'])
.'&name="+id)
});
});'
);
i want the ajax link to be like this http://192.168.1.4/~user/church/backend/web/death/stl_set_relation?id=20&name=1
but with my code i'm not able to pass value of id correctly.
what my code creates is the following url
http://192.168.1.4/~user/church/backend/web/death/stl_set_relation?id=%2Bid&name=20
i also tried like this
$.post("'.\Yii::$app->getUrlManager()->createUrl(['death/stl_set_relation','id'=>'"+id"'])
.'&name="+id)
but it didn't give me the desired result
how can i pass the value of id correctly?
try like this may be it will work..
$.post("'.\Yii::$app->getUrlManager()->createUrl(['death/stl_set_relation','id'=>'"+id+"'])
.'&name="+n);
You can do this in another way that is by using yii\helpers\Url class.
For example :
$this->registerJs(
'jQuery(document).ready(function($){
$(".member").on("change",function(){
var id = $(this).attr("id");
// alert(id);
var n = $(this).val();
// alert(n);
$.post( "'.Url::toRoute('death/stl_set_relation').'", { id: id, name: id });
});
});'
);
I solved the problem using following code
$.post("'.\Yii::$app->getUrlManager()->createUrl(['death/stl_set_relation'])
.'?id="+id+"&relation="+n)
Try this line
$.post("<?php echo \Yii::$app->getUrlManager()->createUrl([\'death/stl_set_relation\']) ?>?id="+id+"&name="+id).
Whatever you are writing in single quotes here will be printed as it is in the JS. You are printing + sign as it is here. Also you are using id inside PHP scope which should not be the case.

Having trouble appending javascript into my html

OK,so I am trying to pull some data from an api. The problem that I have run into is that I am able to find out the information that I am looking for, but am having trouble getting that information out of the console and onto my main index.html page.
Here is my JS code
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
$.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
console.log(info);
});
});
});
Here is my html code
<div id="search">
<h1>API Test</h1>
<input type="search" id="search-keyword">
<button id="myBtn">Try it</button>
</div>
<div id="results"></div>
By doing this, I am able to get pretty much what I am looking for. However I cannot get the data from the console to the actual page.
I have tried appendChild
var bob = document.getElementById(results);
var content = document.createTextNode(info);
bob.appendChild(info);
I have tried innerHTML
var theDiv = document.getElementById(results);
theDiv.innerHTML += info;
..and I have tried .append()
$('#myBtn').click(function() {
$(results).append(info)
})
I'm out of ideas. I realize that I probably have a small problem somewhere else that I am not seeing that is probably the root of this. Much thanks to anyone who can help me with this issue.
"results" needs to be in quotes with regular javascript and for jquery you have already decalred the results variable.
var theDiv = document.getElementById("results");
theDiv.innerHTML += info;
$('#myBtn').click(function(){
results.append(info)
})
Also since you are declaring results outside of your document ready call you have to make sure you html comes before the javascript.
<script>
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
var resultedData = $.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
return info;
});
var resultDiv = document.getElementById("results");
resultDiv.innerHTML += resultedData;
});
});
</script>

print array with js and add html with jQuery

i want to print an array with js and just add to every element some data with html()
the code i use is :
<script type="text/javascript">
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
for(var i=0;i<testArray.length;i++){
document.write(" " +testArray[i]+"<br />").html("is the best");
}
});
</script>
but it doesnt works.
HTML:
<div id="myDIV"></div>
JS:
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
var vPool="";
jQuery.each(testArray, function(i, val) {
vPool += val + "<br /> is the best <br />";
});
//We add vPool HTML content to #myDIV
$('#myDIV').html(vPool);
});
Update:
Added demo link: http://jsfiddle.net/aGX4r/43/
Syntax problem mate!
Let me get that for you!
// first create your array
var testArray = ["test1", "test2", "test3", "test4"];
// faster ready function
$(function(){
for( var i=0; i<testArray.length; i++ ) {
current = testArray[i] + '<br />' + 'is the best'; // this is a string with html in it.
$(current).appendTo("body"); // add the html string to the body element.
}
});
First. document.write it's not a good practice.
Then, you code have a little error: Function (as in document.write) doesn't have html method. Thats a jQuery method.
So, in order to print the array in the body, you could do:
$('p').html(["test1","test2","test3","test4"].join('<br />')).appendTo(document.body);
It's a little difficult to tell what you want to do, but if you want to append to an element in your DOM, use jQuery.append();
for(var i=0;i<testArray.length;i++) {
jQuery('#mydiv').append(testArray[i]);
}

Categories