How to implement a toggle button link? - javascript

<script>
function setSortMethod(param) {
var sortMethod = "#sortMethod";
var asecending = false;
var currUrl = "";
var currSort = "";
var outputUrl = "";
currSort = "sortMethod=" + param;
if ($('#filterPending')[0].checked == false {
outputUrl = (currSort);
}
window.location.href = "?" + outputUrl;
}
</script>
<button type="button" class="btn btn-link" id="action" onclick="setSortMethod('StartDate')" value="LeaveDate">
Leave Date
</button>
So I am trying to get this link button working to toggle between ascending and descending sorting order.
../Index?sortMethod=StartDate which sort the display data by
ascending order
../Index?sortMethod=StartDate_desc will sort the display data by
descending order
I have tried using a boolean variable toggle true/false but to no avail.
Backend c# code I already have the ViewBag with ternary
ViewBag.StartDate = sortMethod == "StartDate" ? "StartDate_desc" : "StartDate";
With switch case it will work if you manually key in the url.
But because right now I am reworking on the link button I changed from actionlink to bootstrap's button link, so I have to find some ways to get the "StartDate" parameter for this onclick="setSortMethod('StartDate') passed into setSortMethod function and try to toggle between StartDate or StartDate_desc.
Trying out razor syntax with ViewBag,
#{
string sortMethod = ViewBag.StartDate;
}
but I am not sure what can I do with this.

Try this One.
<button type="button" class="btn btn-link" id="action" onclick="setSortMethod('StartDate')" value="LeaveDate">
Leave Date
</button>
<script>
function setSortMethod(param) {
var sortMethod = "";
var asecending = false;
var currUrl = "";
var currSort = "";
var outputUrl = "";
currSort = "sortMethod=" + param;
window.location.href += "?" + currSort
}
</script>

Related

How to use different blogger post ID in Javascript variable?

I am trying to make every article views having comma separated every 3 digit number. I have found the code for that.
But I have problem to find specific blogger post ID to use for the code to work fine.
Here's the whole code that I am trying to work on.
<--Viewable area /-->
<span class='entry-time'><b:if cond='data:allBylineItems.author and data:allBylineItems.timestamp.label'><span class='on'><data:allBylineItems.timestamp.label/></span></b:if><time class='published' expr:datetime='data:post.date.iso8601'><data:post.date/></time></span><span class='postviews1' style='margin-left:5px; display:display;'><a expr:name='data:post.id'/> <i class='far fa-eye'/> <span id='bacani'><span id='postviews'/></span> Views</span>
<--comma separated every 3 digit /-->
<script>var angka = document.getElementById('bacani').textContent;var reverse = angka.toString().split('').reverse().join(''),ribuan = reverse.match(/\d{1,3}/g);ribuan = ribuan.join(',').split('').reverse().join('');document.getElementById('bacani').innerHTML= ribuan;</script>
<--code for views count /-->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/> <script> $.each($("a[name]"), function(i, e) { var elem = $(e).parent().find("#postviews"); var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name")); blogStats.once("value", function(snapshot) { var data = snapshot.val(); var isnew = false; if(data == null) { data= {}; data.value = 0; data.url = window.location.href; data.id = $(e).attr("name"); isnew = true; } elem.text(data.value); data.value++; if(window.location.pathname!="/") { if(isnew) blogStats.set(data); else blogStats.child("value").set(data.value); } }); });</script>
I want to change:
<span id='bacani'><span id='postviews'/></span>
and
document.getElementById('bacani').textContent;
to have a specific value id which is post id from blogger. The only thing that i found from internet is
<data:post.id>
Is there any other way that i can make it work other than what I am thinking right now? I think I need specific new id to make it work for every article to have comma separated every 3 digit.
I try to use the code but it only work for one time only. I believe to make it work as a whole I need to use different code to read specific unique id base on data:.post.id from blogger post id itself. But i do not sure how to make it work. I am expecting when I know how to use different method which is making new code that find unique id for different article it would work fine.
You can just replace elem.text(data.value) to
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
The full code would be
<!-- code for views count -->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/>
<script>
/*<![CDATA[*/
$.each($("a[name]"), function (i, e) {
var elem = $(e).parent().find("#postviews");
var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name"));
blogStats.once("value", function (snapshot) {
var data = snapshot.val();
var isnew = false;
if (data == null) {
data = {};
data.value = 0;
data.url = window.location.href;
data.id = $(e).attr("name");
isnew = true;
}
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
data.value++;
if (window.location.pathname !== "/") {
if (isnew) blogStats.set(data); else blogStats.child("value").set(data.value);
}
});
});
/*]]>*/
</script>

How to make dynamic non-repeatable select

I have try to create Dynamic Input group
My expected is
dynamic selection box[length in config var parameter] with...
Non-duplicate select option --> I check when click ,remove and append
Can click to add/remove input group
limited by var parameter
So now My actual result is
not hide will be select option in new select of previous select on append
delete select can't check the repeating after remove
But After i click some where will back to normal as i expect a little because item what i click still no update
So here for long code
Thank for viewing
var parameter =[
"A"
,"B"
,"C"
,"D"
];
$(document).ready(function(e){
$('div.multiselect').append('<div class="selectlist"></div>');
$('div.multiselect').append('<button class="btn btn-outline-light addlist">add search parameter</button>');
$('div.multiselect').append('<button class="btn btn-success search">search</button>');
addSelect();//Create first
$('div.multiselect .addlist').click(function(){
addSelect();
});
});
(function($) {
var origAppend = $.fn.append;
$.fn.append = function () {
return origAppend.apply(this, arguments).trigger("append");
};
})(jQuery);
var selectblock = function (){
var outside = $(document.createElement("div")).addClass('input-group');
var inside = $(document.createElement("select")).addClass('custom-select').on("click append",checkRepeat);
var selVal=[];
$("div.multiselect .selectlist div.input-group").each(function(){
selVal.push($(this).find("select").val());
});
if(selVal.length == parameter.length){
alert("Can't add more parameter");
return;
}
for (var i =0 ; i < parameter.length ; i++){
var option = $(document.createElement("option")).val(parameter[i]).text(parameter[i]);
if($.inArray(parameter[i], selVal) > -1){
option.attr("disabled","disabled").hide();
}
inside.append(option);
}
outside.append(inside);
outside.append($(document.createElement("input")).attr('Type','Text').addClass('form-control'));
var delbtn = $(document.createElement("button")).text("X").addClass('btn btn-danger input-group-append dellist');
delbtn.click(function(){
$(this).parent().remove();
checkRepeat;
});
outside.append(delbtn);
return outside;
};
function addSelect(){
$('div.multiselect .selectlist').append(selectblock);
checkRepeat;
}
var checkRepeat = function (){
//console.log('trigger');
var selVal=[];
$("div.multiselect .selectlist div.input-group").each(function(){
selVal.push($(this).find("select").val());
});
$(this).parent().siblings("div.multiselect .selectlist div.input-group").find("select").find("option").removeAttr("disabled").show().filter(function(){
var a=$(this).parent("select").val();
return (($.inArray(this.value, selVal) > -1) && (this.value!=a));
}).attr("disabled","disabled").hide();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="multiselect">

Pass input text value to javascript not working

Good day. I have read and done almost all of the solution in the questions but cant seem to solve my problem. As written in my question, in mvc, i am passing a value from controller to view a string and then get by javascript to run a modal if ever a certain condition is met. please help. thanks.
here is the code in my controller:
public ActionResult Series()
{
List<sample> series = db.samples.Where(x => x.status == "False").ToList();
if ( series.Count == 0)
{
ViewBag.Info = "None";
}
else {
ViewBag.Series = series;
ViewBag.Info = "Have";
}
return View();
}
My View:
<input type="text" value="#ViewBag.Info" id="info" name="info" />
My Javascript:
#section Scripts{
<script>
$(window).on('load', function () {
var modelll = document.getElementById("#(ViewBag.Info)").value;
var s_end = document.getElementById("myNumber2").value;
var s_current = document.getElementById("myNumber3").value;
var s_status1 = document.getElementById("status").value;
var s_id1 = parseInt(document.getElementById("myNumber").value);
var s_end2 = parseInt(s_end, 10);
var s_current2 = parseInt(s_current, 10);
var x = parseInt(s_current, 10) + 1;
document.getElementById("item1").value = s_id1;
document.getElementById("item2").value = s_end;
document.getElementById("item3").value = x;
document.getElementById("status2").value = s_status1;
if (modelll === 'Have')
{
if ((s_current2 > s_end2) && (s_current2 != s_end2)) {
$('#myModal').modal({ backdrop: 'static', keyboard: false });
$('#myModal').modal('show');
}
}
else
{
$('#myModal').modal({ backdrop: 'static', keyboard:false });
$('#myModal').modal('show');
}
});
</script>
}
getElementById need an ID but you are passing #ViewBag.Info. change it to :
var modelll = document.getElementById("info").value;
also you are making many extra variables which are not really needed. for example to get what you have in s_current2, you can use
var s_current = parseInt(document.getElementById("myNumber3").value, 10);
no need to create another variable to convert it to integer.
To get the value from textbox
var modelll = document.getElementById("info");
To set the value to textbox
document.getElementById("info").value = var modelll;
you are using #ViewBag.Info instead of element id.
Following line is causing the problem in your code :
var modelll = document.getElementById("#(ViewBag.Info)").value;
// document.getElementById needs Id but you are passing #(ViewBag.Info) which is wrong
var modelll = document.getElementById("info").value; //info id of your textbox
// now check
if (modelll === 'Have')
{ }
else
{ }

Change a button label using Javascript

I have a submit button which I am sharing between 'Create' and 'Update'. I want the following labels depending on my page state:
Create = Submit
Update = Update
These buttons also have an image at the front of them using glyphicon but the image will be the same for both buttons.
To get to my page states (listed above) I have other JavaScript functions which the relevant buttons call.
All my code is below. I am struggling as I am fairly new to JavaScript and I now I can do it by adding using Value but this doesn't work due to my image.
Edit Button HTML
<button type="button"class="btn btn-default" name="RegCashMove_Edit_Button" onclick='RegCashMoveEdit()'>
<span class="glyphicon glyphicon-pencil" title="Edit" style="vertical-align: middle"></span>
</button>
Create Button HTML
<button type="button" class="btn btn-default" name="RegCashMove_Create_Button" onclick='RegCashMoveCreate()'>
<span class="glyphicon glyphicon-plus"></span> Create
</button>
Variable Button HTML
This is the button I want the label to be variable on. At the moment its 'Submit'
<button name="RegularCashMovements_Submit_Button" class="btn btn-default" id="RegularCashMovements_Submit_Button" type="submit">
<span class="glyphicon glyphicon-ok"></span> Submit
</button>
JavaScript function for 'Create' button
function RegCashMoveCreate(txt) {
document.getElementById('selection').value = "Create";
document.getElementById('index').value = "";
document.getElementById('RCMViewState').value = "Initial";
document.getElementById('submitAndCancel').style.display = "block";
document.getElementById('editAndConfirm').style.display = "none";
document.getElementById('yesAndNo').style.display = "none";
document.getElementById('confirmTemplate').style.display = "none";
document.getElementById('createEditDeleteTopLine').style.display = "block";
document.getElementById('RegCashMoveHeading').innerHTML = "<h3>" + txt + "</h3>";
document.getElementById('RegCashMoveFields').style.display = "block";
document.getElementById('RegCashMoveDeleteConfirmation').style.display = "none";
document.getElementById('FromDiv').innerHTML = "<%=fromInnerHtml%>";
document.getElementById('ToDiv').innerHTML = "<%=toInnerHtml%>";
document.getElementById('AmountDiv').innerHTML = "<%=amountInnerHtml%>";
document.getElementById('FrequencyDiv').innerHTML = "<%=frequencyInnerHtml%>";
document.getElementById('FromErrorDiv').innerHTML = "";
document.getElementById('ToErrorDiv').innerHTML = "";
document.getElementById('AmountErrorDiv').innerHTML = "";
document.getElementById('FrequencyErrorDiv').innerHTML = "";
document.getElementById('RegCashMove_From_DropDownList').value = "- - Please select - -";
document.getElementById('RegCashMove_To_DropDownList').value = "- - Please select - -";
document.getElementById('RegCashMove_Amount_TextBox').value = "";
document.getElementById('RegCashMove_Frequency_DropDownList').value = "0";
};
JavaScript function for 'Edit' button
function RegCashMoveEdit(txt, from, to, amount, frequency, index) {
document.getElementById('selection').value = "Edit"
document.getElementById('index').value = index;
document.getElementById('RCMViewState').value = "Initial";
document.getElementById('submitAndCancel').style.display = "block";
document.getElementById('editAndConfirm').style.display = "none";
document.getElementById('yesAndNo').style.display = "none";
document.getElementById('confirmTemplate').style.display = "none";
document.getElementById('createEditDeleteTopLine').style.display = "block";
document.getElementById('RegCashMoveHeading').innerHTML = "<h3>" + txt + "</h3>";
document.getElementById('RegCashMoveFields').style.display = "block";
document.getElementById('RegCashMoveDeleteConfirmation').style.display = "none";
document.getElementById('FromDiv').innerHTML = "<%=fromInnerHtml%>";
document.getElementById('ToDiv').innerHTML = "<%=toInnerHtml%>";
document.getElementById('AmountDiv').innerHTML = "<%=amountInnerHtml%>";
document.getElementById('FrequencyDiv').innerHTML = "<%=frequencyInnerHtml%>";
document.getElementById('FromErrorDiv').innerHTML = "";
document.getElementById('ToErrorDiv').innerHTML = "";
document.getElementById('AmountErrorDiv').innerHTML = "";
document.getElementById('FrequencyErrorDiv').innerHTML = "";
document.getElementById('RegCashMove_From_DropDownList').value = from;
document.getElementById('RegCashMove_To_DropDownList').value = to;
document.getElementById('RegCashMove_Amount_TextBox').value = amount;
document.getElementById('RegCashMove_Frequency_DropDownList').value = frequency;
};
I no I should be able to add a variable in each of my JavaScript function to display the relevant label but my issue is getting it on the button with my image
You can set the textual content of a HTML element with the "textContent" property ("innerText" in IE < 9):
var button = document.getElementById('RegularCashMovements');
button.innerText = button.textContent = 'new text';
The span element inside the button element should not be removed.
If you also want to change the title of the span do it like that:
for (var index = 0; index < button.childNodes.length; index++) {
if (button.childNodes[index].tagName == 'SPAN') {
button.childNodes[index].title = 'new title';
break;
}
}
You need to iterate through all child nodes of the button, instead of taking the first one, because than you will get the text content of the button again.
I hope i understood your problem. I also have to say, that your javascript is very procedural and inperformant because of all the "display: none;" and innerHTML accesses. My tip for you would be to think more objective and put all elements you need to hide in one container element and hide that one.

Date entries in the array are not printed

I've just created an dynamic HTML form and two of its fields are of type date. Those two fields are posting their data into two arrays. I have 2 issues:
a) The array data are not printed when I press the button.
b) Since I created the arrays to store the data, my dynamic form doesn't seem to be fully functional. It only produces new fields when I press the first "Save entry" button on the form. It also doesn't delete any fields.
My code is:
$(document).ready(function () {
$('#btnAdd').click(function () {
var $address = $('#address');
var num = $('.clonedAddress').length;
var newNum = new Number(num + 1);
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
newElem.children('div').each(function (i) {
this.id = 'input' + (newNum * 10 + i);
});
newElem.find('input').each(function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$('#btnDel').click(function () {
$('.clonedAddress:last').remove();
$('#btnAdd').removeAttr('disabled');
if ($('.clonedAddress').length == 0) {
$('#btnDel').attr('disabled', 'disabled');
}
});
$('#btnDel').attr('disabled', 'disabled');
});
$(function () {
$("#datepicker1").datepicker({
dateFormat: "yy-mm-dd"
}).datepicker("setDate", "0");
});
var startDateArray = new Array();
var endDateArray = new Array();
function intertDates() {
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
startDateArray[startDateArray.length] = inputs;
endDateArray[endDateArray.length] = inputsend;
window.alert("Entries added!");
}
function show() {
var content = "<b>Elements of the arrays:</b><br>";
for (var i = 0; i < startDateArray.length; i++) {
content += startDateArray[i] + "<br>";
}
for (var i = 0; i < endDateArray.length; i++) {
content += endDateArray[i] + "<br>";
}
}
JSFIDDLE
Any ideas? Thanks.
On your button you are using element ID's several times, this is so wrong, IDs must be unique for each element, for example:
<button id="btnAdd" onclick="insertDates()">Save entry</button>
</div>
</div>
<button id="btnAdd">Add Address</button>
<button id="btnDel">Delete Address</button>
jQuery will attach the $('#btnAdd') event only on the first #btnAdd it finds.
You need to use classes to attach similar events to multiple elements, and in addition to that simply change all the .click handlers to .on('click', because the on() directive appends the function to present and future elements where as .click() only does on the existing elements when the page is loaded.
For example:
<button id="btnDel">Delete Address</button>
$('#btnDel').click(function () {
[...]
});
Becomes:
<button class="btnDel">Delete Address</button>
$('.btnDel').on('click', function () {
[...]
});
Try this : I know its not answer but it's wrong to get element value using id
Replace
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
With
var inputs = document.getElementById('datepicker1').value;
var inputsend = document.getElementById('datepicker2').value;
You are using jQuery so i will strongly recommend you to stick with the jQuery selector,
var inputs = $('#datepicker1').val();
var inputsend = $('#datepicker2').val();
where # is used for ID selector.

Categories

Resources