Materialize css dropdown in input field issue - javascript

My project required auto-suggestion in when user input their query in the input field. I have tried to implement using materialize CSS, Ajax, Django, Jquery as follows:
HTML PAGE:
<div class="row" id ="adddiv">
<div class="input-field col s3">
<input placeholder="Stock Item" type="text" name="StockItem-1" class="validate dropdown-trigger" data-target="dropdown1" id="stockitem">
<ul id="dropdown1" class="dropdown-content">
</ul>
</div>
JS Snippet:
$(function(){
// $("#stockitem").change(function(){
$('.dropdown-trigger').keyup(function(){
$('.dropdown-content').html("")
var query = $('.dropdown-trigger').val();
var data = {'query':query}
var url = 'auto_suggest'
$.ajax({
type: "GET",
url: url,
dataType : 'json',
data: data,
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
success: function(data)
{
var results = data["resultlist"]
$.each(results, function(index,value){
$('.dropdown-content').append("<li>"+ value +"</li>");
});
}
});
});
});
I am able to get the data from backend and li elements are appending with selected ul elements, but it's not displaying as dropdown in front-end.
Refer materialize CSS dropdown:
I suspect the problem with CSS please here

You shouldn't be using the drop down for that, you should be using the autocomplete
https://materializecss.com/autocomplete.html
Also remember to call the Initialization functions as that's what it looks like you are currently missing. With the below modifications it should work. But again, you should be using the autocomplete for this.
$(function(){
///////////////////////////////////////////////
// YOU HAVE TO INITIALIZE THE DROPDOWN
const dropDownEl = $('.dropdown-trigger')[0]
M.Dropdown.init(dropDownEl)
///////////////////////////////////////////////////
// $("#stockitem").change(function(){
$('.dropdown-trigger').keyup(function(){
$('.dropdown-content').html("")
var query = $('.dropdown-trigger').val();
var data = {'query':query}
var url = 'auto_suggest'
$.ajax({
type: "GET",
url: url,
dataType : 'json',
data: data,
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
success: function(data)
{
var results = data["resultlist"]
$.each(results, function(index,value){
$('.dropdown-content').append("<li>"+ value +"</li>");
});
///////////////////////////////////////////////
// YOU HAVE TO OPEN THE DROPDOWN
M.Dropdown.getInstance(dropDownEl).open();
///////////////////////////////////////////////////
}
});
});
});

Related

Populate select option tag with dynamic data from xml link

I need to populate select option tags with dynamic data that I get from an xml link.
Hello, I am working with sharepoint and I need to get a solution for my problem.
I have an empty select tag and I need to fill it with dynamic data from an xml link.
https://scontent.ftun3-1.fna.fbcdn.net/v/t1.15752-9/66477621_1241321552715420_782504330790961152_n.png?_nc_cat=103&_nc_oc=AQlt1rE9uaqZ1xQ5hiMymOPlFsedDuxcpBPMP9C_RTgYJ6s8P5ekStaUIaC5MTiZyOY&_nc_ht=scontent.ftun3-1.fna&oh=bbda50d7782545a433025406a28b2396&oe=5DBECD7B
The data in the picture is statically typed and the name of the column in the xml link is <d:ProjectOwnerName>, but I want it to be dynamic.
starting from this code, how can I do this?
$.ajax({url: _spPageContextInfo.siteAbsoluteUrl + "/_api/ProjectData/[en-US]/Projects",
method: "GET",
dataType: "json",
headers: {Accept: "application/json;odata=verbose"},
success: function(data) {
var dataResults = data.d.results;
var listItemInfo ="";
$.each(dataResults, function(key, value)
{
And this the html part:
<select style="color:black; font-weight:bold;" id="mylist" onchange="myFunction()">
<option></option>
</select>
If your data is xml then use dataType:'xml'. It may be something like this.
$.ajax({url: _spPageContextInfo.siteAbsoluteUrl + "/_api/ProjectData/[en-US]/Projects",
method: "GET",
dataType: "xml",//or json if xml is wrapped in json
//headers: {Accept: "text/xml"},//make sure you need this
success: function(data) {
//check which is your desired XML
console.log(data);
console.log(data.d);
console.log(data.d.results);
//suppose it is data.d.results
var dataResults = data.d.results;
var list = $('#mylist');
$(dataResults).find('d\\:ProjectOwnerName')//this is how access namespaced property
.each(function(){
list.append($('<option />').text(this.innerText));
});//each
}//success
});//$.ajax

Update div content using PHP and Javascript variables

I'm new to Ajax and need some help with this.
The idea is simple, I have a list of directories within the div 'list' and when I click on one of the directories, the div 'content' must list the content of this directory with a php function.
This is my html code:
<div id="list">
<ul>
<li id="directory_1" class="test">directory_1</li>
<li id="directory_2" class="test">directory_2</li>
<li id="directory_3" class="test">directory_3</li>
<li id="directory_4" class="test">directory_4</li>
</ul>
</div>
<div id="content">
<!-- Here you can see the folder content-->
</div>
This my jQuery + Ajax:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
It works, I arrive to list.php. And on PHP I have a function that lists directory content.
So how can I refresh 'content div' with the php function?
So if I click on directory_1 it will show /var/www/pg/directory_1 folders, and then if I click on directory_2 it will clear the 'content' div and will then list out the directory_2 folders.
Here is a jsfidde without the PHP code:
http://jsfiddle.net/e5v1dgpc/
Sorry for my English, if someone has a question I will try to clarify.
You could do something like this:
jQuery('#content').html('');
Which will just set everything inside the html to be blank.
Or I think you could use .empty() - http://api.jquery.com/empty/
If you called it at the start of your function then it should clear the div before repopulating it.
$(".test").click(function(){
var name = $(this).attr("id");
$( "#content" ).empty();
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
In order to set the target of your ajax you could do something like this with a success condition. You'd need to change it to display whatever content you want.
$.ajax({
url: 'list.php',
type: 'POST',
success: function(html) {
var divSuccess = $('#content', $(html)).addClass('updated');
$('#content').html(divSuccess);
}
});
This link might also be useful to you - jquery ajax load certain div
Instead of Emptying the 'content' div initially, you can empty it
OnSuccess of the Ajax post, as below:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
success: function(){
$( "#content" ).empty();
}
});
});
Hope this is what you are looking for..

Checking text of individual divs and changing content

I have repeats of the same code multiple times because of my PHP echoing the content out, and I want to interact with each div separately. It's hard for me to explain, but here's an example of the code repeated just twice. Hopefully it fully represents what I actually have...
<form id="favorite"><div id="images"><input type="submit" style="background-image: url(grey.png);" onclick="submit" value="" /></div></form>
<form id="favorite"><div id="images"><input type="submit" style="background-image: url(grey.png);" onclick="submit" value="" /></div></form>
javascript:
$('#favorite').submit(function() {
var url = document.URL;
if(document.getElementById("images").innerHTML.indexOf("grey") != -1) {
$.ajax({
type: "POST",
url: url,
data: $("#favorite").serialize(),
success: function(data)
{
$('#images').html("<input type=\"submit\" style=\"background-image: url(red.png);\" onclick=\"submit\" value=\"\" />");
}
});
} else {
$.ajax({
type: "POST",
url: url,
data: $("#favorite").serialize(),
success: function(data)
{
$('#images').html("<input type=\"submit\" style=\"background-image: url(grey.png);\" onclick=\"submit\" value=\"\" />");
}
});
}
return false;
});
So, if I were to click the image for the top form, it works perfectly. It will run the PHP and it will change the image without refreshing. If I click the bottom image, it will run the PHP, but it will refresh the page and it won't change the image. So it seems like if I click the bottom one, it doesn't like the Javascript. I don't know if it's because it's looking at both of the forms since they have the same ID (which I can't fix since it could possibly have hundreds), or something else, which I don't see any problems. I'm guessing there's some way to do it using "this", but I'm unsure of how to use it.
Thank you!
You need to change a few things. Your selector to bind the event only matches the first occurrence of #favourite as id's should be unique. You get around this by using an attribute equals selector.
In addition, ensure you select each sub-element in the context of the current form, similar to this:
$('[id=favorite]').submit(function () {
var $form = $(this); // the current form
var $image = $('#images', $form) // get images element in the context of current form
var url = document.URL;
if ($image.html().indexOf("grey") != -1) {
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), // use current form, don't re-select
success: function (data) {
$image.html("<input type=\"submit\" style=\"background-image: url(red.png);\" onclick=\"submit\" value=\"\" />");
}
});
} else {
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), // use current form, don't re-select
success: function (data) {
$image.html("<input type=\"submit\" style=\"background-image: url(grey.png);\" onclick=\"submit\" value=\"\" />");
}
});
}
return false;
});

pass data to lable in same page using jquery

i have this working code with this code i can pass data to div within same page
but insted of passing data to div i want to pass this to label or textbox so that i can post it to the server. i am new in ajax,jquery . please suggest me best answer
<script type="text/javascript">
//send clicker data to div
$(function() {
$(".clicker").mouseover(function(){
var data = $(this).attr('id');
$.ajax({
type: "POST",
data: "db_data=" + data,
success: function(){
//alert(data);
$('.responseDiv').text(data);
}
});
});
});
</script>
<script type="text/javascript">
i think i need to change this line only
$('.responseDiv').text(data);
but dont know how to do that. didnt find any solution on net also
take any name like propertyId
Let's say the text field has id="propertyID"
Use the val() method to assign this new value to your text field.
$('#proertyID').val(data);
Like:
$(function() {
$(".clicker").mouseover(function(){
var data = $(this).attr('id');
$.ajax({
type: "POST",
data: "db_data=" + data,
success: function(){
//alert(data);
// $('.responseDiv').text(data);
$('#proertyID').val(data);
}
});
});
});
In the below line change selector .responseDiv with id/name or class of input/label $('.responseDiv').val(data);
<script type="text/javascript"> //send clicker data to div
$(function() {
$(".clicker").mouseover(function(){
var data = $(this).attr('id');
$.ajax({
type: "POST",
data: "db_data=" + data,
success: function(data2){
//alert(data);
$('.responseDiv').text(data2);
}
});
});
});
success return in data2 and use this..

update div with Ajax MVC4

I can't seem to understand how to update a div of items after a category is selected. I've got this far and am now confused. How to get the values from the view into the controller to make the query?
//get <li> clicked and display the items in that category
$(document).ready(function() {
$('#test li').click(function() {
var selector = "input[name='" + $(this).id + "value']";
var catID = $(selector).val();
$.ajax({
url: "...",
type: "get",
data: {//return all the item info},
success: function(data) {
//update div contents here?
}
});
});
});
Partial to be updated upon which category is clicked
#foreach (var item in Model)
{
<ul>
<li>#item.item_name</li>
<li><input type="hidden" class="item_id" value="#item.ID" /></li>
</ul>
}
Controller
public ActionResult PartialTwo( int id)//how to pass category id?
{
var query = from d in db.Items
where d.catId==id
orderby d.dateAdded
select d;
var results = query;
return PartialView("_FullInfoPartial", results);
//returns items in the clicked category
}
instead of two li
<li>#item.item_name</li>
<li><input type="hidden" class="item_id" value="#item.ID" /></li>
you can just use one in order to decrease dom size if it is not required
<li data-id="#item.ID">#item.item_name</li>
and you can get the partial view result with $.get easily
$("#test li").on("click",function(){
var requestPage = "/PartialTwo?id=" + $(this).data("id");
$.get(requestPage, function(result){
$("#content").html(result); // where you want to put the result
});
});
I've answered a very similar question over here, though the example was using PHP. The basic idea is the same however. your MVC4 will return some data type that will be turned into HTML (the easiest way is to just return straight HTML) and then you will append this HTML value to a DOM element (in this case, the div item of your choice).
the JQuery would look similar too:
var request = $.ajax({
type: "POST",
url: "example.php",
data: data_obj,
dataType: "html"
}).done(function(msg) {
$("#example_element").append(msg);
}
Attempting to load a "div" as dynamic content is returned
Use Ajax.BeginForm as follows,
#using (Ajax.BeginForm("Index", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "youDivId" }))
Using the above and making your controller returning Patial View will update your div with the partial view result.

Categories

Resources