I cannot for the life of me work out how to update bootstrap controls with ASP.Net.
I have the following code:
#{
Layout = null;
}
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title Mark Hub</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<script>
var url = "http://localhost:51520/api/teacher/"
function getTerms(course) {}
//get a reference to the select element
$select = $('#termSelect');
//request the JSON data and parse into the select element
$.ajax({
url: url + "global/currentterms/" + course ,
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.person, function(key, val){
$select.append('<option id="' + val.id + '">' + val.name + '</option>');
})
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});
</script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Mark Hub", "Index", "Teacher", null, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Teacher", "Index", "Teacher")</li>
<li>#Html.ActionLink("Admin", "Index", "Admin")</li>
</ul>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-1 text-left">
<select class="form-control" id="courseSelect" onclick="getTerms()">
<option>DEC 10</option>
</select>
</div>
<div class="col-md-1 text-left">
<select class="form-control" id="termSelect">
</select>
</div>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<hr />
<footer>
<p>© #DateTime.Now.Year</p>
</footer>
</div>
</div>
</div>
</div>
</body>
</html>
I am trying to take the value the user selects (I only have one for convenience at the moment) from the courseSelect control, pass it to my Javascript function getTerms, call a web api and populate the termSelect control dynamically from the returned JSON.
Selecting a value from my courseSelect combobox is not updating my termSelect combobox.
How would I fix my code?
EDITED WITH UPDATE CODE TO REFLECT UPDATES IN ANSWERS
<script>
var url = "http://localhost:51520/api/teacher/"
$(function(){
$('#courseSelect').on('change',function(){
// This is equal to your getTerms function
var course = $('#courseSelect').val();
//request the JSON data and parse into the select element
$.ajax({
url: url + "global/currentterms/" + course,
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.termID, function(key, val){
$select.append('<option id="' + val.id + '">' + val.name + '</option>');
})
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
})
})});
</script>
My code still doesn't work and when I add a breakpoint in VS, the function isn't called on me selecting a value from the select box courseSelect.
You are calling this function getTerms() on click of the select tag.. which is wrong.. you must use on change event . Even click will work but then it will get trigerred even if you click the text box which will do a API call , this is unnecessary request .. Also stop using inline event binder it's deprecated and soon will stop working in future, you must bind event using on in Jquery change your code to below.
Remove the onClick in your HTML
<select class="form-control" id="courseSelect">
<option>DEC 10</option>
</select>
Then in Jquery use this
$(function(){
$('#courseSelect').on('change',function(){
// This is equal to your getTerms function
var course = $(this).val();
// rest of your logic goes here
});
});
your javascript' function is getTerms(course), while you are calling it on your click method as getTerms()
so you should change your javascript as following :
function getTerms() {}
//get a reference to the select element
$select = $('#termSelect');
$course= $('#courseSelect').val(); // this is how you get the value of course
//your next code
Related
I'm loading a popup div dynamically with different html page contents. The HTML page controls are rending on div successfully but the problem is, the whole page is refreshing during loading the content using $("#middlepart").load()
I want to reload the content without refreshing the page in asp.net.
The code is given below:
<div class="popmiddlepart">
<div class="type-benifit">
<div class="subdivOne">
<div class="fl-lt">
<label>Type of Benefit</label>
</div>
<div class="fl-lt">
<div id="ddlBenefitType" >
</div>
</div>
<div class="clearfix"></div>
<hr style="margin-bottom: 10px; margin-top: 10px;">
</div>
</div>
<div id="relate-message-box-html" style="display: none">
<i class="fa fa-info-circle" aria-hidden="true" style="color: red;"></i><strong></strong>
<span id="spnToolTipTexthtml"></span>
</div>
<div class="clearfix"></div>
<div id="middlepart" class="dynamic-content">
<div class="middle-part">
content goes here
</div>
</div>
</div>
I'm updating the div calling the dropdown onchange event
$("#ddlBenefitType").relateSelectControl({
selectControlDataSource: benefittypedata,
dataValueField: 'id',
dataTextField: 'text',
onchange: function (e) {
e.preventDefault();
var selectedtype = $("#ddlBenefitType").getSelectControlText();
if (selectedtype == 'Accommodation') {
var key = getQueryStringValue('id');
$("#middlepart").load(baseUrl + "employee/accomodationdetails_ie.html?id=" + key);
}
if (selectedtype == 'Loan') {
var key = getQueryStringValue('id');
$("#middlepart").load(baseUrl + "employee/loandetails_ie.html?id=" + key);
}
}
});
Try $.get(). It is shorthand for making a jquery ajax call to load the html from an external source asynchronously.
Something like this should work:
$.get( baseUrl + "employee/accomodationdetails_ie.html?id=" + key, function( data ) {
$( "#middlepart" ).html( data );
});
I am working on a bootsrap3 template, which is Ajax based.
My index file has a leftside menu and a conent block middle of the page, every time I click on a subelement of this left menu, an Ajax laod will put the page content in this block(ajax-content).*
Any time I call any page, my URL normally looks something like this /index.php#page-one.php, except when the page contains form submission.
The Problem happens when I add an action attribute (acion="page-one.php") to my form tag.
After the form submission my URL turns to /page-one.php ;
consequently I get a white page containing the page-one.php elements whitout any CSS styling and of course no index-file's elements.
What is the correct and best way to come a cross this issue?
index.php:
<body>
<!--Start Container-->
<div id="main" class="container-fluid">
<div class="row">
<div id="sidebar-left" class="col-xs-2 col-sm-2">
<ul class="nav main-menu">
<li class="dropdown">
<a id="configuration" href="#" class="dropdown-toggle">
<i class="fa fa-gears"></i>
<span class="hidden-xs">Menu-element</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="page-one.php">Menu-Subelement-one</a></li>
<li><a class="ajax-link" href="page-wo.php">Menu-Subelement-two</a></li>
</ul>
</li>
</ul> <!-- end of main-menu-->
</div>
<!--Start Content-->
<div id="content" class="col-xs-12 col-sm-10">
<div class="preloader">
<img src="img.gif" class="loader" alt="preloader"/>
</div>
<!--inside this div a short description/introduction(simple text inside a <p> tag) about the Menu-element will be shown-->
<div id="content-header"></div>
<!--inside this div the page content of the Menu-subelement will be shown-->
<div id="ajax-content"></div>
</div>
<!--End Content-->
</div>
</div>
<!--End Container-->
<script src="plugins/jquery/jquery-2.1.0.min.js"></script>
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<script src="plugin/jquery.form.js"></script>
<script src="js/script.js"></script>
And here is my script.js:
//
// Function for load content from url and put in $('.ajax-content') block
//
function LoadAjaxContent(url){
$('.preloader').show();
$.ajax({
mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
url: url,
type: 'GET',
success: function(data) {
$('#ajax-content').html(data);
$('.preloader').hide();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
dataType: "html",
async: false
});
}
//////////////////////////////////////////////////////
document.ready
//////////////////////////////////////////////////////
$(document).ready(function () {
var ajax_url = location.hash.replace(/^#/, '');
if (ajax_url.length < 1) {
ajax_url = 'home.php';
}
LoadAjaxContent(ajax_url);
$('.main-menu').on('click', 'a', function (e) {
var parents = $(this).parents('li');
var li = $(this).closest('li.dropdown');
var another_items = $('.main-menu li').not(parents);
another_items.find('a').removeClass('active');
another_items.find('a').removeClass('active-parent');
if ($(this).hasClass('dropdown-toggle') || $(this).closest('li').find('ul').length == 0) {
$(this).addClass('active-parent');
var current = $(this).next();
if (current.is(':visible')) {
li.find("ul.dropdown-menu").slideUp('fast');
li.find("ul.dropdown-menu a").removeClass('active')
}
else {
another_items.find("ul.dropdown-menu").slideUp('fast');
current.slideDown('fast');
}
}
else {
if (li.find('a.dropdown-toggle').hasClass('active-parent')) {
var pre = $(this).closest('ul.dropdown-menu');
pre.find("li.dropdown").not($(this).closest('li')).find('ul.dropdown-menu').slideUp('fast');
}
}
if ($(this).hasClass('active') == false) {
$(this).parents("ul.dropdown-menu").find('a').removeClass('active');
$(this).addClass('active')
}
if ($(this).hasClass('ajax-link')) {
e.preventDefault();
if ($(this).hasClass('add-full')) {
$('#content').addClass('full-content');
}
else {
$('#content').removeClass('full-content');
}
var url = $(this).attr('href');
window.location.hash = url;
LoadAjaxContent(url);
}
if ($(this).attr('href') == '#') {
e.preventDefault();
}
});
$('#formSubmit').ajaxForm();
});
page-one.php:
<!--some php code here-->
<form class="validateForm" id="formSubmit" action="page-one.php" method="get">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username" />
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-8">
<button type="submit" class="btn btn-primary btn-label-left">
<span><i class="fa fa-save"></i> Save</span>
</button>
</div>
</div>
</form>
Thanks!
I had the same issue to solve for the intranet I work on.
For me, the good way to do this is to avoid using submit method and use instead an input button with a js function to send the form data.
In my case, I did this:
<!-- At the top of my webpage -->
<script language='Javascript'>
function loadingAjax(div_id,user,date1,date2)
{
$("#"+div_id).html('<br><center><img src="images/loading.gif"><br><br><font color="#006699" face="arial" size="4"><b>Loading data<br>VPlease wait ...</b></font></center>');
$.ajax({
type: "POST",
url: "activities.php?USER="+user+"&DATE1="+date1+"&DATE2="+date2,
success: function(msg){
$("#"+div_id).html(msg);
}
});
}
</script>
<!-- And here is my form -->
<form id='date_form'>
<input type='text' id='user'><input type='text' id='date1'><input type='text' id='date2'>
<input type='button' onclick="loadingAjax('myDiv',document.getElementById('user').value,document.getElementById('date1').value,document.getElementById('date2').value);">
</form>
This allow to send your form in a separate DIV without having to show to everyone your URL.
MORE: you can even use this function to manage your left side menu selection so that your URL would stay '/index.php' all the time.
Hope this help
Regards
Nico
How do you want to submit the form, using ajax?
If you want to use ajax, you should cancel the default action like you do with your links using e.preventDefault();. Post the javascript that handles the form submit if you need help with that.
If you want to post to page-one.php without using ajax, you could add a header() redirect after the php code that processes the form to redirect to the page that you would like to show after the form gets submitted.
As you are loading content by ajax,
You can post content to page-one.php and redirect user to it's previous page. But it will be difficult manage and show error, success, notification message like form validation errors etc.
Another and I think best solution is to use ajax form submission
I'm building a script which grabs some content from a JSON file and dynamically build some html.
The Html is to display some product information as some sort of lookbook.
Inside the html there are a few dropdown boxes. These boxes are also created dynamically. Everything is working fine except that the content from the last dropdownbox is used for every dropdown that is build. See attached image:
I personally think that the reason is why this is happening is because the variants are build and appended before the actual HTML is build??!
$('#sets .set').each( function(){
....
$.getJSON(url, function (data){
var product = data.product;
var $container = $('.products .product');
var productsHtml = [];
$.each(product.related, function(index, rel){
$.getJSON(url, function (data){
var rel = data.product;
var wqsSelectVariants = $('<div class="product-configure-variants tui" />');
var select = $('<select id="product_configure_variants"/>');
$.each(rel.variants, function (index, variant){
select.append('<option value=' + variant.id + '>' + variant.title + '</option>');
wqsSelectVariants.append(select);
});
$('.varianten').html(wqsSelectVariants);
});
var productHtml = '' + '<div class="p"><div class="foto"><img class="rollover" src="'+image+'" hover="'+image2+'" alt="'+rel.fulltitle+'"/></div><div class="prijs" data-price="'+rel.price.price_incl+'">€'+rel.price.price_incl+'</div><div class="varianten"></div></div>';
productsHtml.push(productHtml);
});
productsHtml = productsHtml.join('');
$container.html(productsHtml);
});
});
HTML
<div class="set">
<div class="right">
<div class="products">
<div class="close"></div>
<div class="product">
**-- in here the content from the script example below --**
<div class="p">
<div class="foto">
<a href="zwart.html">
<img alt="Enkellaars zwart" hover="image.jpg" src="image2.jpg" class="rollover">
</a>
</div>
<div data-price="39.95" class="prijs">€39.95</div>
<div class="varianten">
<div class="product-configure-variants tui">
<select id="product_configure_variants">
<option value="9996912">Maat: M/L</option>
</select>
</div>
</div>
</div>
</div>
</div><!-- .products -->
</div><!-- .right -->
<div class="image">
<img src="{{ product.image | url_image('220x330x2', product.fulltitle) }}" width="220" height="330" alt="{{ product.fulltitle }}" />
</div>
</div>
Does any body know what I'm doing wrong??
WIthin the loop of $('#sets .set').each() the current instance of .set is this.
So you can isolate the '.varianten' for each .set by traversing within the current instance only
$('#sets .set').each( function(){
var $variant =$(this).find('.varianten');
/* do all the ajax stuff */
});
Then change the line:
$('.varianten').html(wqsSelectVariants);
To
$variant.html(wqsSelectVariants);
Note that ID's must be unique in a page also.
I am trying to implement a vote up/down functionality on comments.
For that, I've placed two buttons in every comment. Using jQuery's each() and click() functions, I am trying to get the button's id that was clicked, fire an ajax request to aother page, and then disable both vote up/down buttons for that specific comment using the success() callback.
For initial verification of whether it works or not, I'm trying this on just two comments i.e. 4 buttons, and then disabling a specific pair of them, irrespective of which button is clicked.
I've tried 3-4 different selector queries, but the only one that works is where I specifically pass the exact id attribute's value of the button that I click on. I need to implement this in a general fashion, on a page with multiple comments and their buttons!!
Here's the PART of the HTML code on which I'm trying to use the jQuery:
<section class="section content">
<div class="content-wrapper">
<div class="zone-content equalize zone clearfix">
<div class="content-container container-16">
<div class="comments block">
<div class="block-title-2">
<h2>Comments on Place X</h>
</div>
<div class="review-messages">
<div class="review first">
<div class="review-author">
<b>
<span class="author">John</span> - <span class="date">April 10, 2013 at 7:34 pm</span>
</b>
</div>
<br>
<div class="review-text">
Best place to have abcdef food in yyyyy. !!!
</div>
<br>
<!-- xxxxxxx SELECT ONE OF THESE TWO --> <button class="btn btn-circle btn-success" id="test_id_1"><i class="glyphicon glyphicon-thumbs-up"></i></a></button>
<!-- xxxxxxx SELECT ONE OF THESE TWO --> <button class="btn btn-circle btn-danger" id="test_id_2"><i class="glyphicon glyphicon-thumbs-down"></i></a></button>
</div>
<div class="review last">
<b>
<div class="review-author">
<span class="author">John</span> - <span class="date">April 10, 2013 at 7:34 pm</span>
</div>
</b>
<br>
<div class="review-text">
<p id="text1">Great xxxx and a good place to yyyy :)</p>
</div>
<br>
<!-- xxxxxxx SELECT ONE OF THESE TWO --> <button class="btn btn-circle btn-success" id="test_id_3"><i class="glyphicon glyphicon-thumbs-up"></i></a></button>
<!-- xxxxxxx SELECT ONE OF THESE TWO --> <button class="btn btn-circle btn-danger" id="test_id_4"><i class="glyphicon glyphicon-thumbs-down"></i></a></button>
</div>
</div>
<div class="comment-message">
<div class="comment-message-title">
Leave a <span class="text-colorful">Comment</span>
</div>
<form class="comment-message-form">
<textarea class="text-input-grey comment-message-main" placeholder="Your Comments Here"></textarea>
<div class="thin-separator"></div>
<input type="submit" class="button-2-colorful to-right" value="Post Comment" name="comment" />
</form>
</div>
</div>
</div><!-- end of .content-container -->
</div><!-- end of .zone-content -->
</div><!-- end of .content-wrapper -->
</section>
Here are the various jQuery selector codes I've tried:
1. DOESN'T WORK
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('div button[id^="test_id_"]').each(function(){
$(this).click(function(e){
var name = {"name":$(this).attr("id")};
$.ajax({
url: 'receiveajax.php',
data: name,
type: 'POST',
}).success(function(data) {
$(this).attr("disabled",true);
});
});
});
});
</script>
2. DOESN'T WORK
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('button').click(function(e){
$('button[id^="test_id_"]').each(function(){
var name = {"name":$(this).attr("id")};
$.ajax({
url: 'receiveajax.php',
data: name,
type: 'POST',
}).success(function(data) {
$(this).attr("disabled",true);
});
});
});
</script>
3. SPECIFIC ELEMENT SELECTOR QUERY. WORKS.
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#test_id_1").click(function(e){
var name = {"name":$(this).attr("id")};
$.ajax({
url: 'receiveajax.php',
data: name,
type: 'POST',
}).success(function(data) {
$("#test_id_1,#test_id_2").attr("disabled",true);
});
});
});
</script>
And this is the page that will receive the Ajax POST request, implemented as a simple stub. I've also used it's echo output in the success() callback to print it, so as far as I'm concerned, this file doesn't have any errors. Probably. :
<?php
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
echo "Welcome ". $name;
}
?>
1) Your loops are complex which is not need.
2) Inside the success callback, this is not your button, you should keep a reference to it.
3) Using prop for disabled attribute is preferred.
$(document).ready(function() {
$('button').click(function(e){
var $button = $(this);
var name = {"name": $button.attr("id")};
$.ajax({
url: 'receiveajax.php',
data: name,
type: 'POST',
}).success(function(data) {
$button.prop("disabled", true);
});
});
});
Your code is very close but you don't need to iterate buttons using .each(), simply bind click event and you will get instance of clicked button i.e. $(this) and use that instance to disable the button. see below code -
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('button[id^="test_id_"]').click(function(e){
var name = {"name":$(this).attr("id")};
$.ajax({
url: 'receiveajax.php',
data: name,
type: 'POST',
}).success(function(data) {
$(this).attr("disabled",true);
});
});
});
</script>
I am trying to implement something like this. IF you click the button it would get the HTML of the above elements and insert them in an alert :
<div id="0001">
<h5 class="title">Hello World </h5>
<h4 class="date">2014-07-19 </h4>
<button onclick="addCalendar('#0001. #title','#0001. #date')"> Add to Calendar </button>
</div>
<div id="0002">
<h5 class="title">Bye Bye</h5>
<h4 class="date">2014-07-22 </h4>
<button onclick="addCalendar('#0002. #title','#0002. #date')"> Add to Calendar </button>
</div>
<script>
function addCalendar(title,date){
alert(title + ": " + date);
}
</script>
This code should works..
If you want to get the value of that HTML:
$("button").click(function(){
var value = $(this).siblings("#title").text();
value += $(this).siblings("#date").text();
alert(value);
});
If you want to get the HTML tags too:
$("button").click(function(){
var value = $(this).siblings("#title").html();
value += $(this).siblings("#date").html();
alert(value);
});