Reputation: 9301
Depending if the Model has any content or not, I would like to change the background color of a HTML element with jQuery in the View. But this isn't working like I want, because the document is already loaded inside the DOM and the PartialView just change a small part of the document and the script will not run more than the first time. Is there a way to solve this in another way?
This is my code that I thought should work:
@if (Model.Any())
{
<script>
$(document).ready(function () {
$("#Filter").addClass("match");
});
console.log("Det matchar!!");
</script>
Show content of list here
}
else
{
<p>No Match!</p>
<script>
$(document).ready(function () {
$("#Filter").addClass("noMatch");
});
console.log("Ingen match!!");
</script>
}
EDIT 1: It's the input element I want to change, and that is inside of the index.cshtml file.
EDIT 2: I have also tested to call a simple javascript function inside the index file from the View, like this:
<script>
checkMatch();
</script>
I could pass values like "no" or "yes" and then depending on the input parameter change the input element. But I'm not sure the call is made when the code inside the PartialView is inserted.
EDIT: 3 Sorry, I forgot to write that the partial view is updated with AJAX. I guess that could be one problem!?
EDIT: 4 It's seems like it's working now! When I moved away the javascript function that at first was within the jQuery document.ready code, it worked by calling a function inside of the index file! Thanks all of you who tried to help me! And it didn't work with jQuery .addClass
, but it worked with .css
to change the background color of the element that way. My question is solved!
Upvotes: 0
Views: 687
Reputation: 3202
document.ready
wont work here.place you js code in script tag directly.
try this
@if (Model.Any()) {
<script>
$("#Filter").addClass("match");
console.log("Det matchar!!");
</script>
Show content of list here } else {
<p>No Match!</p>
<script>
$("#Filter").addClass("noMatch");
console.log("Ingen match!!");
</script>
}
Upvotes: 1
Reputation: 1696
A simpler way to achieve this would be to add the appropriate CSS class to the HTML before returning it from the server. There are various ways to do this with Razor, but perhaps the easiest is something along these lines:
@if (Model.Any()) {
<div id="Filter" class="match">
}
else {
<div id="Filter" class="noMatch">
}
Upvotes: 1