How can I link a select2 multi-select dropdown to another select2 multi-select dropdown? - dropdown

In my SharePoint page, I have a single selection dropdown DP that is linked to a multi-selection dropdown Category. The values of Category are appended when DP is selected. I want to change DP to multi-selection and still have Category linked to it so that the values of Category will be added-on if more than one DP is selected. How can I do this?
<body>
<div class="form-group">
<label>DP</label>
<select class="form-control select2" id="sp_DP" multiple>
</select>
</div>
<div class="form-group">
<label>Category</label>
<select class="form-control select2" id="spCategory" multiple>
</select>
</div>
</body>
<script>
$('[id*="sp_DP"]').on('change', function()
{
//$('#spCategory').empty();
var dpName = $(this).find("option:selected").text();
AddCategories(dpName);
});
function LoadDPOptions()
{
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('DP')/items?$select=ID,Title&$orderby=Title asc&$top=200",
headers: {
Accept: "application/json;odata=verbose"
},
async: false,
success: function(data) {
if (data.d.results.length > 0)
{
$('[id*="sp_DP"]').append($("<option></option>").attr("value", 0).text(""));
for (var i = 0; i < data.d.results.length; i++)
{
var item = data.d.results[i];
$('[id*="sp_DP"]').append($("<option></option>").attr("value", item .ID).text(item.Title));
}
}
},
error: function(data) {
console.log("An error occurred. Please try again.");
}
});
}
function AddCategories(dpName)
{
if(dpName)
{
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('DP')/items?$select=ID,Title,Category/ID,Category/Title&$expand=Category&$filter=Title eq " + encodeURIComponent("'" + dpName + "'"),
headers: {
Accept: "application/json;odata=verbose"
},
async: false,
success: function(data) {
if (data.d.results.length > 0)
{
var item = data.d.results[0];
var catsArr = item.Category["results"];
catsArr.sort(function(a, b) {
var t1 = a.Title.toUpperCase();
var t2 = b.Title.toUpperCase();
return (t1 < t2 ) ? -1 : (t1 > t2 ) ? 1 : 0;
});
for(var i = 0; i < catsArr.length; i++)
{
var result = catsArr[i];
$('#spCategory').append($("<option></option>").attr("value", result.ID).text(result.Title));
}
}
},
error: function(data) {
console.log("An error occurred. Please try again.");
}
});
}
}
</script>

Related

how to remove an uploaded images

Here I have tried to remove a uploaded images. Like while if user clicks on any of the images which is uploaded by the user if we click on cross icon it has to remove the images. So below is my code where I have tried and I am able to remove the image but at once multiple images are removing i need to remove only selected images not multiple so how can we do that. all images should have cross icon at the top corner. Please
Vue.config.productionTip = false;
new Vue({
el: '#app',
data() {
return {
files: [],
images: null,
}
},
computed: {
filesNames() {
const fn = []
for (let i = 0; i < this.files.length; ++i) {
fn.push(this.files.item(i).name)
}
return fn
}
},
methods: {
handleFileUploads(event) {
this.files = event.target.files;
this.images = [...this.files].map(URL.createObjectURL);
},
removeImage: function () {
this.images = null
},
submitFile() {
let formData = new FormData();
for (var i = 0; i < this.files.length; i++) {
let file = this.files[i];
formData.append('files[' + i + ']', file);
}
axios.post('/multiple-files', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(function() {
console.log('SUCCESS!!');
})
.catch(function() {
console.log('FAILURE!!');
});
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
<h2>Multiple Files</h2>
<hr/>
<label>
<span>Files</span>
<input type="file" multiple #change="handleFileUploads($event)" />
<ul v-if="files.length">
<li v-for="(name, i) in filesNames" :key="i">{{ name }}</li>
</ul>
</label>
<div>
<img v-for="image in images" :src="image" />
<button v-if="images" #click="removeImage()" type="button">×</button>
</div>
<br />
<button #click="submitFiles()">Submit</button>
</div>

Making a value from a fetch call available immediately

I have a Go program written that has a form which checks for the existence of a file by calling a fetch on a route inside the Go code. If the file exists or not, a boolean is return inside of a JSON as fileExists. I'm having trouble with the fetch call's JSON updating this.found boolean immediately.
What happens is that when I press enter or click the buttons, the form is submitted via call to onSubmit where the checkFile() is called which does the fetch. Somehow, I have to press enter twice to see the value returned by the fetch as it is not updating the this.found immediately. I am probably thinking about this the wrong way, but I figure it wouldn't to ask. Here's the code, if anyone can help so that clicking or submitting will be based on the correct value returned by the checkFile call:
<div class="jumbotron">
<div class="container">
<div class="alert alert-dark" role="alert">
</div>
<h1 class="display-3">Title</h1>
<div id="app">
<form ref="myForm" method="POST" v-on:submit.prevent="onSubmit" action="/push" class="needs-validation" id="myForm" novalidate="true">
<div class="form-group">
Canned List:
<input v-model="cannedlist" ref="cannedlist" type="text" class="form-control" name="fileListFile" id="filelist"
aria-describedby="fileListFileHelp"
autocomplete="off" :disabled="!!individuallist" v-on:submit.prevent="onSubmit" />
</div>
<div class="form-group">
Path List:
<textarea v-model="individuallist" ref="cannedlist" :disabled="!!cannedlist" class="form-control" rows=10 name="fileListRaw" id="files" autocomplete="off"></textarea>
</div>
<div class="form-group">
<button v-on:submit.prevent="onSubmit" type="submit" name="button" value="submit" id="submitButton" class="btn btn-primary" :disabled="isDisabled">Submit</button>
<button v-on:submit.prevent="onSubmit" type="submit" name="button" value="checkOnly" id="checkOnlyButton" class="btn btn-primary" :disabled="isDisabled">Submit 2</button>
</div>
</form>
</div>
</div>
</div>
<script src="/static/js/vue.min.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
// cannedlist: "filelist.txt",
individuallist: "",
found: false,
},
computed: {
isDisabled: function() {
//found = !found;
return (this.cannedlist.length <= 0 && this.individuallist.length <= 0);
},
},
methods: {
isDisabledNew: function() {
alert((this.cannedlist.length <= 0 && this.individuallist.length <= 0));
// return (this.cannedlist.length <= 0 && this.individuallist.length <= 0);
return false;
},
isFieldDisabled: function(e) {
//console.log(app.$refs.individuallist.disabled);
return false;
},
onSubmit: function() {
if (this.cannedlist.length > 0) {
this.checkFile();
if (this.found == true) {
this.$refs.myForm.submit();
return;
}
} else if (this.individuallist.length > 0) {
this.$refs.myForm.submit();
return;
}
},
checkFile: function() {
var url = 'http://localhost:9000/CheckIfFileExists?name=' + this.cannedlist;
return fetch(url)
.then(response => {
if (response.ok) {
var v = response.json().then( response => { this.found = response.fileExists; } );
return this.found;
}
return response.json().then(error => ({ error }));
});
return this.found;
},
}
});
</script>
Your onSubmit function calls checkFile and expects found to be updated:
onSubmit: function() {
if (this.cannedlist.length > 0) {
this.checkFile();
if (this.found == true) {
this.$refs.myForm.submit();
return;
}
} else if (this.individuallist.length > 0) {
this.$refs.myForm.submit();
return;
}
},
But checkFile returns a Promise. The Promise resolves by updating found. So you need to put your found checking inside a then block:
onSubmit: function() {
if (this.cannedlist.length > 0) {
this.checkFile()
.then(() => {
if (this.found == true) {
this.$refs.myForm.submit();
}
});
return;
} else if (this.individuallist.length > 0) {
this.$refs.myForm.submit();
return;
}
},
Here're the changes I made:
methods: {
onSubmit: function(event) {
if (this.cannedlist.length > 0) {
this.checkFile()
// This promise capture is the key I was missing
.then( (data) => {
this.found = data.fileExists;
if (this.found == true) {
this.$refs.myForm.submit();
} else {
alert("File not found: " + this.cannedlist);
}
});
} else if (this.individuallist.length > 0) {
this.$refs.myForm.submit();
}
},
checkFile: function() {
var url = 'http://localhost:9000/CheckIfFileExists?name=' + this.cannedlist;
return fetch(url).then((response) => response.json());
}

keep selected item of dropdownlist as you move from page to page in a webgrid

I have a page that has a dropdownlist and a webgrid. The webgrid has pagenumbers. If I am on page 1 and I select page 2 the item
selected on the dropdown is lost and goes back to "Select Branch"
I want to be able to keep the item selected as I move from page to page. How do I do that? I tried the request.form but did not work
public ActionResult Index()
{
var currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
Edmviewmodel objedmtest = new Edmviewmodel();
string ddlState_SelectedStateValue = Request.Form["ddlDropDownList"];
if (currentUser != null)
{
try
{
objedmtest = _edmDataService.GetRequiredData("A05");
ViewData["SelectList"] = HttpContext.Session["SelectList"] ?? new List<string>();
}
catch (Exception ex)
{
//logger.Error(ex);
}
}
return View(objedmtest);
}
Here is the html code.
#{
var grid = new WebGrid(source: Model.GetCatDataByLocation,
defaultSort: "CustomerName",
canSort: true,
rowsPerPage: 5
);
}
<div>
<div>
<label for="ddlBranch">Branch:</label>
#Html.DropDownList("ddlDropDownList", Model.BranchesSelectList, "Select Branch", new { #class = "css-class" })
</div>
<div>
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Select", format: #<text><input name="CustomerName" type="checkbox" value="#item.CustomerName" #Html.Raw(((List<string>)ViewData["SelectList"]).Contains(#item.CustomerName) ? "checked" : "") /></text>),
grid.Column("CustomerName", "CustomerName"),
grid.Column("CustomerNumber", "CustomerNumber"),
grid.Column("Orderdate", "Orderdate", canSort: false),
grid.Column("OrderNumber", "OrderNumber"),
grid.Column("Routenumber", "Routenumber"),
grid.Column("Primaryrep", "Primaryrep"),
grid.Column("Isvalidated", "Isvalidated")
)
)
</div>
<div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
//check for existance of query string
var urlg = window.location.href; //global url
var previousIndex = 0;
if (urlg.indexOf("ap") > 0) {
previousIndex = (urlg.substring(urlg.indexOf("ap=") + 3));
}
$('select>option:eq(' + previousIndex + ')').prop('selected', true); //zero-based
$("a").click(function (event) {
$("td a").each(function () {
var old = $(this).attr('href');
idx = $("select[name='ddlDropDownList'] option:selected").index();
$(this).attr("href", old + "&ap=" + idx);
});
});
});
</script>

JqWidget tabs - dynamically add tab with ajax content

I want create a dynamic on click append data to tab but I get in the tab undefined. Could you tell me whats wrong? Not quite sure what is the case,
My js
<script type="text/javascript">
$(document).ready(function () {
// Create jqxTabs.
$('#jqxTabs').jqxTabs({ width: 580, height: 200,showCloseButtons: true });
var length = $('#jqxTabs').jqxTabs('length') + 1;
var loadPage = function (url) {
$.get(url, function (data) {
data;
// console.log( $('#content' + length ).text(data));
// console.log(data);
});
}
$('div.s span').click(function() {
var getvalue = $(this).attr('rel');
$('#jqxTabs').jqxTabs('addFirst', 'Sample title',loadPage(getvalue).text());
$('#jqxTabs').jqxTabs('ensureVisible', -1);
});
// $('#jqxTabs').on('selected', function (event) {
// var pageIndex = event.args.item + 1;
// loadPage('pages/ajax' + pageIndex + '.htm', pageIndex);
// });
});
</script>
My html
<div class="s">
<span rel="gen.php">Load</span>
</div>
<div id='jqxWidget'>
<div id='jqxTabs'>
<ul>
</ul>
</div>
</div>
So first check the right syntax for tab control:
HTML:
....
<div id='jqxTabs'>
<ul>
<li></li>
</ul>
<div></div>
</div>
Javascript:
// Create jqxTabs.
$('#jqxTabs').jqxTabs({ width: 580, height: 200, showCloseButtons: true });
$('#jqxTabs').jqxTabs("removeFirst"); //here removes the empty tab
//here the function must return the content, and the ajax must be async false for this purpose
var loadPage = function (url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
$('div.s span').click(function() {
var getvalue = $(this).attr('rel');
$('#jqxTabs').jqxTabs('addFirst', 'Sample title', loadPage(getvalue));
$('#jqxTabs').jqxTabs('ensureVisible', -1);
});
For better understanding check: http://jsfiddle.net/charlesrv/h4573ykv/1/
EDIT: For the new condition, use a custom attribute so checking would be easier:
$('div.s span').click(function() {
var getvalue = $(this).attr('rel');
var opened = $(this).attr('opened');
if (!opened) {
$(this).attr('opened', true);
$('#jqxTabs').jqxTabs('addFirst', 'Sample title', loadPage(getvalue));
$('#jqxTabs').jqxTabs('ensureVisible', -1);
}
});

Watin. how to show invinsible class

HTML code:
<div class="col-sm-9">
<input name="NewCardOrAccountNumber" class="form-control ui-autocomplete-input" id="NewCardOrAccountNumber" type="text" value="" autocomplete="off">
<span class="ui-helper-hidden-accessible" role="status" aria-live="polite"></span>
</div>
<div class="unvisible" id="clientInfoNew">
<div class="form-group">
<label class="col-sm-3 control-label">FIRST NAME</label>
<div class="col-sm-9" id="FnameNew"></div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">LAST NAME</label>
<div class="col-sm-9" id="LnameNew"></div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">BIRTH DATE</label>
<div class="col-sm-9" id="BirthDateNew"></div>
</div>
Watin code:
[TestMethod]
[TestCategory("Rimi Change card page")]
public void Rimi_4444_Change_Card_and_Assert()
{
//Web Address
using (IE ie = new IE(this.Rimi))
{
//IE ie = new IE(RimiChangeCard);
ie.BringToFront();
ie.ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle.Maximize);
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
If I write card number from keyboard, the invisible class appear, and you can see FIRST NAME, LAST NAME and so on. But if I do this with watin, it does not appear, and you only see card number which you input. Its like hidden fields of information. I do not know how to make that I could see this fields when I input card number.
There would be a JavaScript function, which gets executed when you manually enter the data in the text field.Go through the Java Script functions on the same page which refer to that element using it's ID NewCardOrAccountNumber.
Refer to this link for sample application. Where msg_to is element, and has a KeyUp event associated. When that filed gets a , value, there is a div section inside which a `Subject' field is shown.
Similarly, after executing the TypeText, try to trigger related event mentioned in the Java Script event using Java script execution.
EDIT: I see that the javascript functions gets executed after bulr event is fired. This means the textbox field should loose the focus. Try the below options.
// 1. Try focusing out of control.
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
ie.TextField(Find.ById("OldCardOrAccountNumber")).Click();
ie.WaitForComplete();
// 2. Try Using Send Keys method to tab out.
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
System.Windows.Forms.SendKeys.SnedWait("{TAB}"); // Need to add System.Windows.Forms reference to the project.
I put image on the internet, so click on this link Image and you will see on first image how look page, second picture - what have to happen when you input card number (from keyboard), third - what happen when card namuber is input from watin (does not appear information about card).
HTML code:
<div class="ibox-content">
<br>
<div class="form-horizontal">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label class="col-sm-3 control-label">NEW CARD</label>
<input name="NewCardId" id="NewCardId" type="hidden" value="0" data-val-required="The NewCardId field is required." data-val-number="The field NewCardId must be a number." data-val="true">
<div class="col-sm-9"><span class="ui-helper-hidden-accessible" role="status" aria-live="polite"></span><input name="NewCardOrAccountNumber" class="form-control ui-autocomplete-input" id="NewCardOrAccountNumber" type="text" value="" autocomplete="off"></div>
</div>
<div class="unvisible" id="clientInfoNew">
<div class="form-group">
<label class="col-sm-3 control-label">FIRST NAME</label>
I maybe find what you looking for Sham, but I do not know how to use it :
<script type="text/javascript">
$(document).ready(function() {
var NewCardId = "#NewCardId";
var OldCardId = "#OldCardId";
var NewCardNumber = "#NewCardOrAccountNumber";
var OldCardNumber = "#OldCardOrAccountNumber";
$(NewCardNumber).autocomplete(
{
source: function(request, response) {
$.ajax({
url: '/LoyaltyWebApplication/Suggestion/GetCardSuggestions',
dataType: "json",
data: {
str: $(NewCardNumber).val()
},
success: function(data) {
response($.map(data, function(item) {
var label = "";
if (item.Fname != null) label += item.Fname;
if (item.Lname != null) label += " " + item.Lname;
if (label.trim() != '') label = " (" + label.trim() + ")";
return {
value: item.CardNumber,
label: item.CardNumber + label
}
}));
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
},
select: function(event, ui) {
getCardDetails($(NewCardNumber), $(NewCardId), 'newCardSegments', true);
$("#newCardSegments").hide();
$("#clientInfoNew").show();
},
minLength: 2
}).blur(function() {
getCardDetails($(NewCardNumber), $(NewCardId), 'newCardSegments', true);
});
$(OldCardNumber).autocomplete(
{
source: function(request, response) {
$.ajax({
url: '/LoyaltyWebApplication/Suggestion/GetCardSuggestions',
dataType: "json",
data: {
str: $(OldCardNumber).val()
},
success: function(data) {
response($.map(data, function(item) {
var label = "";
if (item.Fname != null) label += item.Fname;
if (item.Lname != null) label += " " + item.Lname;
if (label.trim() != '') label = " (" + label.trim() + ")";
return {
value: item.CardNumber,
label: item.CardNumber + label
}
}));
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
},
select: function(event, ui) {
getCardDetails($(OldCardNumber), $(OldCardId), 'oldCardSegments', false);
$("#oldCardSegments").hide();
},
minLength: 2
}).blur(function() {
getCardDetails($(OldCardNumber), $(OldCardId), 'oldCardSegments', false);
});
function getCardDetails(cardNumHolder, cardIdHolder, segmentTablePlace, isNew) {
$.getJSON('/LoyaltyWebApplication/LOV/SetId?lovType=ReplacementLOV&lovValue=' + cardNumHolder.val(), null,
function(data) {
$("#clientInfo" + ((isNew) ? "New" : "Old")).show();
if (cardNumHolder.val() == '') {
return;
}
var i;
for (i = 0; i < data.otherNames.length; i++) {
$("#" + data.otherValues[i] + (isNew ? "New" : "Old")).text(data.otherNames[i]);
}
cardIdHolder.val(data.Id);
$.getJSON('/LoyaltyWebApplication/Replacement/ClientSegmentsList?clientId=' + data.Id + "&no_cache=" + Math.random, function(data) {
$("#" + segmentTablePlace).find('tbody').empty();
if (data.length > 0) {
$.each(data, function(index) {
$("#" + segmentTablePlace).find('tbody').append("<tr><td>" + data[index].SegmentCode + "</td><td>" + data[index].SegmentName + "</td></tr>");
});
$("#" + segmentTablePlace).show();
}
});
});
}
$("#resetVal").click(function() {
$("#NewCardOrAccountNumber").attr("value", "");
$("#NewCardOrAccountNumber").val("");
$("#NewCardId").attr("value", "");
$("#NewCardId").val("");
$("#clientInfoNew").hide();
$("#OldCardOrAccountNumber").attr("value", "");
$("#OldCardOrAccountNumber").val("");
$("#OldCardId").attr("value", "");
$("#OldCardId").val("");
$("#clientInfoOld").hide();
return false;
});
});
</script>