How to use a javascript function inside class attribute of an element - javascript

I want to create a dynamic 'li' elements and want to assign some classes to the 'li' element by a javascript function based on some parameters in the load of the page
I mean i want the function to run on all the 'li' elements i assign the function to.
something like :
in design
<li class="nav-item someFunction("param1","param2")">
</li>
and the 'someFunction' is a javascript function that returns some classes as a string
to make the 'li' element as follows in the end :
after rendering
<li class="nav-item cssClass1 cssClass2 cssClass3 cssClass4">
</li>

Not exactly how you asked it, but here is how you do it with jquery:
CodePen: https://codepen.io/anon/pen/XeJKVL
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.red{
color:red;
font-size:25px;
}
</style>
<script>
window.onload = function() {
$( "#example" ).addClass("red");
}
</script>
<li id="example">Example</li>

$(document).ready(function(){
$("#ifValueBtn").on("click",function(){
var iFinput=$("#ifValue").val();
if(iFinput==1)
$(".nav-item").addClass("cssClass1");
else if(iFinput==2)
$(".nav-item").addClass("cssClass1 cssClass2");
else
$(".nav-item").addClass("cssClass1 cssClass2 cssClass3");
console.log($(".nav-item").attr("class"));
});
});
.cssClass1{color:red;}
.cssClass2{border:solid 1px #000;}
.cssClass3{font-size:20px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ifValue" type="number" value="1"/>
<input id="ifValueBtn" type="button" value="Click"/>
<hr>
<ul>
<li class="nav-item">
test
</li>
</ul>

Actually I figured out the answer from you people answered ideas
I create the li items dynamically so I tried to create all the markup for it from database but it didn't work as the functions calls are being copied as string without parsing or compiling it of course
so
I have made the following function :
function someFuncionConvertedItsCodeFromServerSide(parameter1, parameter2,...) {
//somecode that debend on some server side functions, collections, session values, properties
// return css as string
}
and get some parameters from the db as follows in the ajax call example :
$.ajax({
type: 'POST',
url: 'url',
dataType: 'json',
success: function (result) {
for (var i = 0; i < result.array.length; i++) {
var css = someFuncion(result.array[i].id, other parameters .. );
var liItem = "<li class=\"nav-item " + css + " id=\"" + result.array[i].id + "\"> <span class=\"title\" > " + someText + " </span > </li>";
$("#ulId").append(liItem);
}
}
});
so as you can see I created an id for every created li to combine the parameters in one place that can be sent to a javascript function to return the css classes as a string as needed
It's a prototype code of course it needs some modification but that what is done and worked
thank you all guys trying to help I get the idea from our discussion together
tell me If i didn't mark the right answer

Related

How Can I call a dynamic index in function cshtml?

I have this function :
<script>
function f(id){
return $("#" + id).val();
}
</script>
And this html's tag:
<input id=f(#payMethod) type="radio" value=" #method.Value" name="cartaCont" />
My id is buildered with a foreach that pass value to variable:
string payMethod = "payMethod";
payMethod += method.Text;
My question is: Is correct Call this index in an other function in this way ?? :
function() {
$('input[id ^= #PayMethod]').attr('checked', headerChecked);
}
thanks for feedback
It seems that you want to write some html and javascript code, relating to each item of a list.
In this case, I often prefer to directly write html and related javascript for event binding and code customization.
I supposing that method is your razor variable in your foreach, and methods is the enumerable variable to loop, you may would write this code for html
#foreach(var method in methods)
{
// this is C#, not javascript
// replacing spaces to build right id code for html
string payMethod = "payMethod" + method.Value.Replace(" ", "");
<text>
<input id="#payMethod" class="payMethodRadio" type="radio" value="#method.Value" name="cartaCont" />
<script>
$(document).ready(function () {
$("##payMethod").on('change', function (e) {
/* here if you want to write some javascript events for each item related to its html ID, for example change event */
});
});
</script>
</text>
}
But if you want to write some common jQuery code for this set of radio buttons, I' prefer to manage it with class selector rather than ID rules, as follow
function() {
$('payMethodRadio')...
}
Hope this, help you for better code management.
Br
Andryx
Try to add Onchange event to input.Here is a demo code:
#{var payMethod = 0;}
#foreach (var method in Model.Methods)
{
<input id="#payMethod" type="radio" value=" #method.Value" name="cartaCont" onchange="Add(#payMethod)"/>
payMethod++;
}
js:
function Add(id) {
$('#'+id).attr('checked', headerChecked);
}

How can I use jquery events to pass variables to php?

I have a form with a drop-down to select a time for scheduling
I didn't use a selector input, instead I used the following html to make the menu for styling reasons.
<div class="tabs">
<div class="apt-time">
<h3>#Time</h3>
<ul class="time-list">
<li class="available">8:00am</li>
<li class="available">9:00am</li>
<li class="available">10:00am</li>
<li class="available">11:00am</li>
<li class="available">12:00am</li>
<li class="available">1:00pm</li>
<li class="available">2:00pm</li>
<li class="available">3:00pm</li>
<li class="available">4:00pm</li>
<li class="available">5:00pm</li>
</ul>
</div>
</div>
Because of this I can't use the POST method to get the data the user clicked on in the menu. So I tried to come up with a solution that could pass a string variable with events to my php page with the GET method in the code below. The if statements are going to be used so the client can't submit the form without clicking on an option in the menu. Is there a way around this without using a selector input?
$('.available').click(function() {
return clockTime = $(event.target).text()
})
$('.btn').click(function() {
if ($('.available').click) {
window.location.href = "textsms.php?"+clockTime
} else {
// warn client that they need to chose a time
}
})
Added AJAX functionality below. The script passes POST values to PHP script named textsms.php without refreshing browser.
Updated Code:
<script>
$('.available').click(function() {
var clockTime = $(this).text();
$.ajax({
url:"textsms.php",
method:"POST",
data:{'clockTime':clockTime,var2:'2',}, // modify fields
success: function(data){
alert(data); // Do something with data received
},
});
});</script>
For testing..
textsms.php:
<?php
print_r( $_POST );
?>
You're not defining the get variable in the redirection:
window.location.href = "textsms.php?"+clockTime
The following will store the "clockTime" in the $_GET['time']
window.location.href = "textsms.php?time="+clockTime
Edit: Anyway your JS is not correct.
var clockTime;
$('.available').click(function(e) {
clockTime = $(this).text();
})
$('.btn').click(function() {
if(typeof clockTime !== "undefined"){
window.location.href = "textsms.php?time="+clockTime
}else{
// warn client that they need to chose a time
}
});
You can use a control variable for this (also defining a css class that show the selected option):
var selectedTime = '';
$('.available').click(function() {
$('.available').removeClass('clicked');
$(this).addClass('clicked');
selectedTime = $(this).text();
})
$('.btn').click(function() {
if (selectedTime != '') {
window.location.href = "textsms.php?time="+selectedTime;
} else {
// warn client that they need to chose a time
}
})
You need to get the value and pass it to your location properly:
$("ul.time-list").on("click","li.available",function(){
var selectedTime = $(this).text();
window.location.href = "textsms.php?varname="+selectedTime;
});
I like using jquery's on event as it allows you to use load content dynamically so long as you target an external static element.
http://api.jquery.com/on/

how to remove the element with defined value from the list?

I would like to create a javascript function to remove an element from the list. The (unfinished) function is the following:
function removeUser(gData) {
var divUsers = document.getElementById('users');
console.log(divUsers);
var userId = gdata.Id(); //the element with this value should be removed from the list - e.g. if userId == 21367, 'Silvana' should be removed.
divUsers.remove(userId);
}
the divUsers looks like the following:
<ul id="users">
<li data-bind="text :FirstName, click:AddOwnerToUser.bind($data), value: Id" style="cursor:pointer" value="21367">Silvana</li>
<li data-bind="text :FirstName, click:AddOwnerToUser.bind($data), value: Id" style="cursor:pointer" value="23295">John</li>
</ul>
As a javascript newbie I would be very thankful if anyone could tell how to get the right element by its id and remove it.
Thanks!
You could use attribute selector [attribute=value] in Element.querySelector, and Element.removeChild to do what you intend to..
function removeUser(gData) {
var divUsers = document.getElementById('users');
console.log(divUsers);
var userId = gdata.Id();
divUsers.removeChild(divUsers.querySelector('[value=' + userId + ']'))
}
The above is how you remove the element as is asked in your question. Do take care if it affects any possible frameworks you'll be using as the first comment to my answer states.

Dynamically populate markup with XML data using javascript variables

I'm on a .NET 4.0 environment using jQuery and Visual Studio to write everything, but neither of these facts should matter that much except how to populate the XML data.
I'm starting out with this script which has a lot of markup in it. My task is to get the markup out of the script and to populate the the XML data into the markup in its proper place. I'm trying to keep the presentation and behavior layers as separate as possible by doing this.
function addIcons(IconType) {
var li ="";
var onclickMethod="";
for (var item in hashObject) {
var thumbNail = item.split("_");
if (thumbNail[0] == IconType +"ThumbNail") {
var imagePath = baseUrlThumbNailImages + hashObject[item];
li = li + "<li onclick=IconClick('" + IconType +"',"+ thumbNail[1] + ")><img src=\"" + imagePath + "\" alt=\"" + IconType + " shape\"></li>\n";
}
}
$("#" + IconType + "ThumbNailShapes").append(li);
}
Here's example markup I want as final result:
<ul>
<li onclick="IconClick('Item',1)">
<img src="/images/image_1.png" alt="Item shape" />
</li>
<li onclick="IconClick('Item',2)">
<img src="/images/image_2.png" alt="Item shape" />
</li>
<li onclick="IconClick('Item',3)">
<img src="/images/image_3.png" alt="Item shape" />
</li>
</ul>
While I know I need to take out the line of code that starts li = li + ..., I'm also not familiar enough with OOP to understand how to write a for loop to populate the markup.
So there's two factors that I am not sure how to code:
The blank markup - does the markup need variables to populate it or should javascript do this automatically?
The javascript - I don't know how to recode the javascript to find each list item and image tag to populate the various data.
Do I need the markup to be blank like this, where all the variable data is not there yet?
<ul id="IconThumbnailShapes">
<li onclick="">
<img src="" alt="shape" />
</li>
<li onclick="">
<img src="" alt="shape" />
</li>
<li onclick="">
<img src="" alt="shape" />
</li>
</ul>
I appreciate the insight and help.
I would do it like this.
Let's suppose we have a container DIV#foo where all this code has to reside.
<div id="foo"></div>
We then do this:
$(function() {
// DOM ready
$('#foo').on('click', '#IconThumbnailShapes li', function() {
// Do whatever you have to do with icon
// Second argument there '#IconThu... li' means the event will be trigerred
// as soon as you add your icons, but they don't have to be there
// right now.
});
function addIcons(iconType) {
var s = '<ul id="IconThumbnailShapes">'
var l = '<li><img src="$SRC" alt="$ICON shape" /></li>'
var data = [{...}, {...}, {...}];
var len = data.length;
var datum;
for (var i = len; i; i--) {
datum = data[len - i];
s += l.replace('$SRC', datum.src).replace('$ICON', iconType);
}
s += '</ul>';
$('#foo').html(s);
}
});
So, we do it like this, because we don't want to fire jQuery stuff in the for loop. That kills performance. Instead we set up a deferred even handler for click on the conainer DIV#foo, and we shove the whole bunch of markup into the container as a string.

jquery ajax method being repeated even though click event not correct

I have some ajax on my web page, that is triggered via a click event, the javascript in question looks like this,
$('.career_select .selectitems').click(function(){
var selectedCareer = $(this).attr('id');
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
buildSelects();
$('.grade_options .selectitems').addClass('select_1')
}
});
});
This part of the ajax request works fine. What happens on success is that I load in another view into my page, this view has some more user interaction that fires some more ajax however, it just fires the previously used method, where as it should be doing the following,
$('.grade_options .selectitems').click(function(){
var selectedGrade = $(this).attr('id');
alert(selectedGrade);
})
The HTML+PHP looks like this,
<div class="grade_options">
<input value="" name="grade" class="customselect" type="hidden">
<div class="iconselect">Have you got any of the following?</div>
<div style="display: none;" class="iconselectholder">
<div class="selectoptions">
<div id="1" class="selectitems hoverclass selectedclass select_1">
<span>Accountant</span>
</div>
<div id="2" class="selectitems">
<span> Grade D's at GCSE including English and Maths</span>
</div>
<div id="3" class="selectitems">
<span>3 GCSE's at grade B and 3 GCSEs at grade C or equivalent and you must have achieved at least a grade C in GCSE English Language & B in Maths</span>
</div>
</div>
</div>
<noscript>
<input type="submit" value="Next" name="submit_grades" class="arr" />
</noscript>
</div>
The .selectitems get created from a select menu using this plugin,
$.fn.customSelect = function() {
// define defaults and override with options, if available
// by extending the default settings, we don't modify the argument
return this.each(function() {
obj = $(this);
obj.after("<div class=\"selectoptions\"> </div>");
obj.find('option').each(function(i){
$(".selectoptions").append("<div id=\"" + $(this).attr("value") + "\" class=\"selectitems\"><span>" + $(this).html() + "</span></div>");
});
obj.before("<input type=\"hidden\" value =\"\" name=\"" + this.name + "\" class=\"customselect\"/><div class=\"iconselect\">" + this.title + "</div><div class=\"iconselectholder\"> </div>")
.remove();
$('.iconselectholder').hide();
$(".iconselect").click(function(){
$(".iconselectholder").toggle("slow");});
$(".iconselectholder").append( $(".selectoptions")[0] );
$(".selectitems").mouseover(function(){
$(this).addClass("hoverclass");
});
$(".selectitems").mouseout(function(){
$(this).removeClass("hoverclass");
});
$(".selectitems").click(function(){
$(".selectedclass").removeClass("selectedclass");
$(this).addClass("selectedclass");
var thisselection = $(this).html();
$(".customselect").val(this.id);
$(".iconselect").html(thisselection);
$(".iconselectholder").toggle("slow")
});
});
// do the rest of the plugin, using url and settings
}
I am struggling to see any reason as to why my second ajax request is running the method of the first ajax request.
Your code seems somewhat incomplete, but I think I can help you.
Where is the class .career_select in the HTML+PHP example you have given? My guess is that .career_select is wrapping .grade_options due to your append:
$('.hfeed').append(html) am I correct? .grade_options was part of the html that got appended right?
If I am correct, then the newly appended HTML would not have had event handlers tied to it ahead of time and hence your second event handler is not firing. I think there are two things you can do:
Declare the new event handler for $('.grade_options .selectitems') in the success function of the first event handler AFTER the append.
If that doesn't work then just do what Paul Sweatte instructed you to do (look at the comments), unbind the original click event in the success callback or if you are sure it is a one-off thing, take a look at jQuery's $(selector).one().
I hope this helps. If the second one works, please remember to give points to Paul Sweatte's comment.

Categories

Resources