In a c# MVC project, I was given a view by a front-end designer that contains this little script:
<script>
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
$('.ProcessDD').hide();
if (chosenValue == "")
$('#DefaultProcess').show();
if (chosenValue == "Planning")
$('#PlanningProcess').show();
if (chosenValue == "Procurement")
$('#ProcurementProcess').show();
if (chosenValue == "Installation")
$('#InstallationProcess').show();
if (chosenValue == "Closure")
$('#ClosureProcess').show();
});
</script>
I would like to replace all the hard-coded options with a list that comes from the model. Something like this...
<script>
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
$('.ProcessDD').hide();
if (chosenValue == "")
$('#DefaultProcess').show();
// loop over a list from the model here
if (chosenValue == " loop-item-name ")
$('# loop-item-name + Process').show();
// end loop
});
</script>
Is this possible? If so, how? And am I even going about this the right way? I was thinking I could use razor syntax, but that isn't working.
You can not compare a C# variable to a JS variable. But you can use razor to create a JS variable from a C# variable.
Here is how to fill a JS array with the values of a C# array:
#{
// fetch this from ViewModel if it needs to be dynamic
var cSharpNames = new [] { "Planning", "Procurement"};
}
<script>
var jsNames = []; // this is a JS array
#foreach(var name in cSharpNames) {
<text>jsNames.push(#name);</text>
}
</script>
Then use the indexOf() method to search in the jsNames array as has been shown by Jeremy.
I'd just make an array, check to see if the value exists within it, and if it does show it. Something like this:
<script>
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
var processes = ['Planning', 'Procurement'];
$('.ProcessDD').hide();
if (chosenValue == "")
$('#DefaultProcess').show();
if (processes.indexOf(chosenValue) > -1)
$('#' + chosenValue + 'Process').show();
});
</script>
I was overthinking this.
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
$('.ProcessDD').hide();
if (chosenValue == "")
{
$('#DefaultProcess').show();
}
else
{
$('#' + chosenValue + 'Process').show();
}
});
Related
Been stuck on this for a while and wanted to get some input as to what I can do differently. I'm essentially taking user input and pushing it into an array, creating a button based on that input, then saving that array to localStorage. When the browser is refreshed, I want to grab that string and re-create those same buttons. Here is what I've got so far:
function generateButton() {
var create = $("<button>")
create.attr("class", "btn btn-outline-secondary")
create.attr("type", "button")
create.text(response.name)
buttonDiv.prepend(create)
var cityString = response.name
cityButtonArr.push(cityString)
localStorage.setItem("cityStorage", JSON.stringify(cityButtonArr))
console.log(cityButtonArr)
as well as:
function loadData(){
var loadData = localStorage.getItem("cityStorage")
var loadedArr = JSON.parse(loadData)
//
if(loadedArr != null && loadedArr != ""){
cityButtonArr.push(loadedArr)
for(i=0; i<cityButtonArr.length;i++){
var create = $("<button>")
create.attr("class", "btn btn-outline-secondary")
create.attr("type", "button")
create.text(cityButtonArr[i])
buttonDiv.prepend(create)
}
}
It works almost perfectly, but instead of loading individual parts of the array ("atlanta","las vegas", "salt lake city") it only creates one button with the text of (atlantalasvegassaltlakecity). How can I break up the array when using JSON.parse? Or am I going about this all wrong?
function loadData() {
var loadData = localStorage.getItem("cityStorage")
if (loadData == null || loadData == "") return;
var cityButtonArr = JSON.parse(loadData)
for (i = 0; i < cityButtonArr.length; i++) {
var create = $("<button>")
create.attr("class", "btn btn-outline-secondary")
create.attr("type", "button")
create.text(cityButtonArr[i])
buttonDiv.prepend(create)
}
}
Full code
I try to create a generator for lucky numbers. I did it with C# and now with JavaScript and jQuery. You can see this here. When I add new field - JQ do not see it. Just try to click on numbers in "Your field". I have as standard 7 fields and they work fine but when I add new line script do not recognise it like something useful. Could you give me some advice?
change below js code. check this working plunker
Your code:
$('.spielzahlen').on('click', function() {
var list = []
tablereset()
var item = $(this).text().split(', ')
item.forEach(function(index) {
if (index != "")
list.push(index)
})
console.log($(this).text())
list_temp = list
$(this).empty()
$('#temp').val(list)
var tds = document.getElementsByTagName("td")
list.forEach(function(index) {
var idt = index - 1
tds[idt].className = 'checked'
})
changeLen(list_temp.length)
})
Change it with below code , there is only change in initialization other code are same :
$(document).on('click','.spielzahlen', function() {
var list = []
tablereset()
var item = $(this).text().split(', ')
item.forEach(function(index) {
if (index != "")
list.push(index)
})
console.log($(this).text())
list_temp = list
$(this).empty()
$('#temp').val(list)
var tds = document.getElementsByTagName("td")
list.forEach(function(index) {
var idt = index - 1
tds[idt].className = 'checked'
})
changeLen(list_temp.length)
})
I have some problem with redirecting urls after checkboxes are selected. I am using document.location for this, but this doesn´t work in my code. I'm trying to fix it, but without success.
This is the part of my code which doesn't work:
function objednat() {
var adress = "";
if (document.getelementbyid('BoxtarifVolani1').checked == true) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/' + adresa;
}
I want to redirect this to a form, which will be filled with the selected values. I don't know why, but this document.location doesn't work in the code.
This is the part of the code I use in the formula for grabbing the hash from the url.
<script type="text/javascript">
if(window.location.hash) {
//set the value as a variable, and remove the #
var hash_value = window.location.hash.replace('#', '');
if (tarifVolani1 == true) {
document.getelementbyid('BoxtarifVolani1").checked = true;}
....
</script>
What am I doing wrong?
Whatever you have done is right, except, the function name is wrong case:
Change getelementbyid to getElementById.
Change adresa to adress.
Code:
function objednat() {
var adress = "";
if (document.getElementById('BoxtarifVolani1').checked == true) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/' + adress;
}
jQuery way of doing it
function objednat() {
var adress = "";
if ($('#BoxtarifVolani1').is(':checked')) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/'+adress;
}
For your ref: jQuery :checked Selector
I have a JQuery function that fetches and displays a page worth of images through the use of JSON files. I want to display the next set of images upon a button click, but that requires adding on a short string to the request url, which is found and stored in a var when I first run the script. I need to call this JQuery function again and pass the string var to it (lastId in code below). I am an utter noob with JavaScript in general and don't know how to go about doing that.
Here is a full version of the code:
$(function runthis(un){
var lastId;
un = typeof un !== 'undefined' ? un : "";
$('#domainform').on('submit', function(event){
event.preventDefault();
$('#content').html('<center><img src="img/loader.gif" alt="loading..."></center>');
//var lastId;
var domain = $('#s').val();
var newdomain = domain.replace(/\//g, ''); // remove all slashes
var requrl = "http://www.reddit.com/r/";
var getmore;
getmore = "?after=t3_"+un;
var fullurlll = requrl + domain + ".json" + getmore;
$.getJSON(fullurlll, function(json){
var listing = json.data.children;
var html = '<ul class="linklist">\n';
for(var i=0, l=listing.length; i<20; i++) {
var obj = listing[i].data;
var votes = obj.score;
var title = obj.title;
var subtime = obj.created_utc;
var thumb = obj.thumbnail;
var subrdt = "/r/"+obj.subreddit;
var redditurl = "http://www.reddit.com"+obj.permalink;
var subrdturl = "http://www.reddit.com/r/"+obj.subreddit+"/";
var exturl = obj.url;
var imgr = exturl;
var imgrlnk = imgr.replace("target=%22_blank%22","");
var length = 14;
var myString = imgrlnk;
var mycon = imgrlnk;
var end = mycon.substring(0,14);
myString.slice(-4);
var test1 = myString.charAt(0);
var test2 = myString.charAt(1);
var timeago = timeSince(subtime);
if(obj.thumbnail === 'default' || obj.thumbnail === 'nsfw' || obj.thumbnail === '')
thumb = 'img/default-thumb.png';
if(end == "http://i.imgur" ){
$("#MyEdit").html(exturl);
html += '<li class="clearfix">\n';
html += '<img src="'+imgrlnk+'" style="max-width:100%; max-height:750px;">\n';
html += '</li>\n';
html += '<div class="linkdetails"><h2>'+title+'</h2>\n';
/*html += '<p class="subrdt">posted to '+subrdt+' '+timeago+'</p>'; /*'+test1+test2+'*/
html += '</div></li>\n';
}
if (listing && listing.length > 0) {
lastId = listing[listing.length - 1].data.id;
} else {
lastId = undefined;
}
} // end for{} loop
htmlOutput(html);
}); // end getJSON()
}); // end .on(submit) listener
function htmlOutput(html) {
html += '</ul>';
$('#content').html(html);
}
});
The way you currently are executing the function run this doesn't ever leave you a handle to that function. This means it only really exists in the context of document.ready (what $(function()) is a shortcut for).
What you want to do instead is to keep a reference to this function for later use.
If you want to be able to put it directly into an onclick='' you will need to put the function in global,
eg:
var myFunction = function() { /*Stuff here*/}
$(myFunction)
this declares a function called myFunction and then tells jQuery to execute it on document ready
Global is generally considered pretty naughty to edit. One slightly better option would be to assign the click to the button inside your javascript
eg:
$(function(){
var myFunction = function() { /*Stuff here*/}
myFunction(); //call it here
$('#my-button-id').click(myFunction);//attach a click event to the button
)
This means that the function myFunction only exists in the scope of your document.ready, not in global scope (and you don't need onclick='' at all)
tTo add listener on some event you can use live('click',function(){}) Like yhis:
<div id="my-button">some content</div>
<script type="text/javascript">
$('#my-button').live('click',function(){
//your code
})
</script>
in my mvc razor view, I have these codes:
#if (Model != null) {
if (Model.Meals != null)
{
var grid = new WebGrid(Model.Meals, defaultSort: "MDate");
double Total = Model.Meals.Where(x => x.FINtravelID == Model.FINtravelID).Sum( t =>t.MTAmount);
And in the script header, I need to get the data of "Total" above in this code:
$(function () {
$("#grid tbody").append('<tr><td><b>Total</b></td><td><b>' + Total.toFixed(2) + '</b> </td></tr>');
})
I have tried to add # in front of Total, but it does not compile, anybody kow how to make it working?
You won't be able to retrieve Total outside of the code block unless you nest it within an element or a hidden input and then retrieved that data with JS. So, for example, if your code looked like this:
#if (Model != null)
{
if (Model.Meals != null)
{
var grid = new WebGrid(Model.Meals, defaultSort: "MDate");
double Total = Model.Meals.Where(x => x.FINtravelID == Model.FINtravelID).Sum( t =>t.MTAmount);
<div id="Total">#Total</div>
}
}
You could grab the data with JS, but you will need to cast the value as a number in order to use the isFixed() method on it because JS implicitly types as string. So use Number() to convert string => double:
<script type="text/javascript">
$(function() {
var total = Number(document.getElementById('Total').innerHTML).toFixed(2);
$("#grid tbody").append('<tr><td><b>Total</b></td><td><b>' + total + '</b> </td></tr>');
});
</script>