JQuery unable to get value from dynamically added Inputs - javascript

I have this script here that I intend to run:
<script>
$(document).ready(function () {
var sd = $("#StartDate").val();
var ed = $("#EndDate").val();
$("#userReportGenerate").click(function (e) {
e.preventDefault();
console.log(sd);
console.log(ed);
$("<input/>").attr("type", "hidden").attr("id", "uStartDate").attr("name", "StartDate").attr("value", sd).appendTo("userReportForm");
$("<input/>").attr("type", "hidden").attr("id","uEndDate").attr("name", "EndDate").attr("value", ed).appendTo("userReportForm");
console.log($("#uStartDate").val());
return false;
});
});
</script>
However, when I click on the button, I get no value for the uStartDate ID. It just appears as blank on my console.
Is it possible to get the value from this input?
I intend to pass the StartDate and EndDate alongside my form when I submit it.

$(document).ready(function () {
var sd = $("#StartDate").val();
var ed = $("#EndDate").val();
$("#userReportGenerate").click(function (e) {
e.preventDefault();
let uStartDate='<input type="hidden" id="uStartDate" name="StartDate" value="'+sd+'">';
$('#userReportForm').append(uStartDate);
return false;
});
});

Related

Getting to specific data in jQuery

I am trying to add an ability to change the contents of one of the columns in the data table (its data cells should be editable). I was using this tutorial as a reference:
https://www.youtube.com/watch?v=LbhVVN5ffi0
its source code:
https://github.com/divanov11/table-edit-backend
And so, I have the following functions in my template:
function edit_description(place){
var targetId = $(this).attr("id");
var value = $(this).text();
var targetIN = $(this).attr("identificationNumber");
$(this).unbind();
$(this).html(`<input class="description form-control" data-target="${targetId}" type="text" value=${value}>`);
$(`.description`).on('keypress', function(e){
if (e.which == 13) {
var target = $(this).attr("data-target");
var description = $(`#${target}`).text($(this).val());
save_description(description, targetIN);
return false;
}
})
}
function save_description(description, identification_number){
console.log('Saved!');
var user_input = {"identificationNumber":identification_number, "description":description};
update_description_POST(user_input);
}
After typing in for example "chipset" I get the following description's value:
<td identificationnumber = "1234" id="description-1234">chipset</td>
I would need the description's value to be just "chipset". How to achieve that?

How to check when input value is changed?

How can i check when a value on input is changed.
I have a calendar and when i click on calendar it changes the value on input , but when im trying to see if it has changed its not working. i have tried AddEventListener, also jquery on change, also i sent a function on change to call it but none of them is working.
<input type="text" id="date" class="date" onchange="changed()" name="" >
function changed(){
alert("hello world");
}
Main js file for creating the calendar :
This function creates the calendar on my php file .
And then when on click it gets the value on the input with id #date
But When im trying to see if value has changed it is not working .
// Initialize the calendar by appending the HTML dates
function init_calendar(date) {
$(".tbody").empty();
$(".events-container").empty();
var calendar_days = $(".tbody");
var month = date.getMonth();
var year = date.getFullYear();
var day_count = days_in_month(month, year);
var row = $("<tr class='table-row'></tr>");
var today = date.getDate();
// Set date to 1 to find the first day of the month
date.setDate(1);
var first_day = date.getDay();
// 35+firstDay is the number of date elements to be added to the dates table
// 35 is from (7 days in a week) * (up to 5 rows of dates in a month)
for(var i=0; i<35+first_day; i++) {
// Since some of the elements will be blank,
// need to calculate actual date from index
var day = i-first_day+1;
// If it is a sunday, make a new row
if(i%7===0) {
calendar_days.append(row);
row = $("<tr class='table-row'></tr>");
}
// if current index isn't a day in this month, make it blank
if(i < first_day || day > day_count) {
var curr_date = $("<td class='table-date nil'>"+"</td>");
row.append(curr_date);
}
else {
var monthplusone = months[month];
var curr_date = $("<td class='table-date' id='"+day+"-"+monthplusone+"-"+year+"'>"+day+"</td>");
var events = check_events(day, month+1, year);
if(today===day && $(".active-date").length===0) {
curr_date.addClass("active-date");
let x = document.getElementById('date').value=day+"-"+monthplusone+"-"+year;
$('.table-date').ready(function () {
x.value;
});
show_events(events, months[month], day);
}
// If this date has any events, style it with .event-date
if(events.length!==0) {
curr_date.addClass("event-date");
}
// Set onClick handler for clicking a date
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
curr_date.click({events: events, month: months[month], day:day}, date_click);
row.append(curr_date);
}
}
// Append the last row and set the current year
calendar_days.append(row);
$(".year").text(year);
}
Notice that change is actually triggered when the input is not focused anymore.
document.getElementById("date").addEventListener("change", function () {
alert("hello world");
});
<input type="text" id="date" class="date" name="">
This works. Not sure where you're running into an issue.
function changed(){
console.log("hello world");
}
<input type="text" id="date" class="date" onchange="changed()" name="" >
EDIT: Shortened version of init_calender() for others interested in answering:
function setDate() {
document.getElementById("date").value = '19-Dec-2021'
}
I basically agree with #Spankied in that you should try and shorten your code to the point where you are having the issue. However, after looking at your code it seems to me that you want the following function
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
to not only change the value in your #date input but also trigger its change event-handler function. You can do that by changing it to something like
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
$("#date" ).change();
});
jQuery.change() without any arguments will trigger a predefined "change"-event on the DOM-object that is selected by the jQuery-object.
You can use js to do that:
let x = $(...) //select the input box
let val = x.value;
function repeat() {
if (val !== x.value) {
change()
}
}
setInterval(repeat, 100)
This checks if the result is the same.
This might make your site a bit slow and it might look odd but this will work in just every case
<script>
let Oldvalue = $('.date')[0].val();
setInterval(() => {
let currentValue = $('.data')[0].val()
if (Oldvalue != currentValue){
//do whatever but in end write this
Oldvalue = currentValue;
}
}, 10);
</script>

How can I add validation to an Input field? Binding JSON model doesn't work

I try to learn SAPUI5 with Samples frpm Demo kit Input - Checked. I get an error message: oInput.getBinding is not a function
I have a simple input field xml:
<Label text="Name" required="false" width="60%" visible="true"/>
<Input id="nameInput" type="Text" enabled="true" visible="true" valueHelpOnly="false" required="true" width="60%" valueStateText="Name must not be empty." maxLength="0" value="{previewModel>/name}" change= "onChange"/>
and my controller:
_validateInput: function(oInput) {
var oView = this.getView().byId("nameInput");
oView.setModel(this.getView().getModel("previewModel"));
var oBinding = oInput.getBinding("value");
var sValueState = "None";
var bValidationError = false;
try {
oBinding.getType().validateValue(oInput.getValue());
} catch (oException) {
sValueState = "Error";
bValidationError = true;
}
oInput.setValueState(sValueState);
return bValidationError;
},
/**
* Event handler for the continue button
*/
onContinue : function () {
// collect input controls
var that = this;
var oView = this.getView();
var aInputs =oView.byId("nameInput");
var bValidationError = false;
// check that inputs are not empty
// this does not happen during data binding as this is only triggered by changes
jQuery.each(aInputs, function (i, oInput) {
bValidationError = that._validateInput(oInput) || bValidationError;
});
// output result
if (!bValidationError) {
MessageToast.show("The input is validated. You could now continue to the next screen");
} else {
MessageBox.alert("A validation error has occured. Complete your input first");
}
},
// onChange update valueState of input
onChange: function(oEvent) {
var oInput = oEvent.getSource();
this._validateInput(oInput);
},
Can someone explain to me how I can set the Model?
Your model is fine and correctly binded.
The problem in your code is here, in the onContinue function
jQuery.each(aInputs, function (i, oInput) {
bValidationError = that._validateInput(oInput) || bValidationError;
});
aInput is not an array, so your code is not iterating on an array element.
To quickly fix this, you can put parentheses around the declaration like this:
var aInputs = [
oView.byId("nameInput")
];
Also, you could remove the first two lines of the _validateInput method since they are useless...
Usually, we set the model once the view is loaded, not when the value is changed. For example, if you would like to set a JSONModel with the name "previewModel", you can do as mentioned below.
Note that onInit is called when the controller is initialized. If you bind the model properly as follows, then the oEvent.getSource().getBinding("value") will return the expected value.
onInit: function(){
var oView = this.getView().byId("nameInput");
oView.setModel(new sap.ui.model.json.JSONModel({
name : "HELLO"
}), "previewModel");
},
onChange: function(oEvent) {
var oInput = oEvent.getSource();
this._validateInput(oInput);
},
...
Also, for validating the input text, you can do the following:
_validateInput: function(oInput) {
var oBinding = oInput.getBinding("value");
var sValueState = "None";
var sValueStateText = "";
var bValidationError = false;
if(oBinding.getValue().length === 0){
sValueState = "Error";
sValueStateText = "Custom Error"
}
oInput.setValueState(sValueState);
if(sValueState === "Error"){
oInput.setValueStateText(sValueStateText);
}
return bValidationError;
},
Please note that the code above is not high quality and production ready as it's a quick response to this post :)

JQuery Values are not changing

#Html.ActionLink("Search", "GetDateWiseGuestReport", "Reports", new { StartDate = "sss",EndDate="eee" }, new { #id = "btnDateWiseGuestSearch", #class = "btn btn-red" })
$("#btnDateWiseGuestSearch").bind('click', function () {
//Get the id of the selected item in dropdown
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
this.href = this.href.replace("sss", StartDate);
this.href = this.href.replace("eee", EndDate);
});
Okay i am using above code to change the Action-link URL at run time.Everything is running smoothly. but i have a strange issue i.e. when i click the button 1st time its gets the values from text boxes and change accordingly, but when i press button again its doesn't get new values from text boxes rather its somehow using OLD VALUES that i inputted 1st time!
Because after the firs click you are replacing the sss and eee from the href so there after is no sss or eee in the href. So nothing is replaced after the first click
So a possible solution is to store the original href value somewhere else then use that for replacing the content. In the below solution the data api is used to store the original value
var $btn = $("#btnDateWiseGuestSearch");
$btn.data('href', $btn.attr('href'))
$btn.bind('click', function () {
//Get the id of the selected item in dropdown
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
var href = $(this).data('href');
this.href = href.replace("sss", StartDate).replace("eee", EndDate);
});
Basically in your jQuery code you are create a new link by replacing sss and eee however once you have replaced them that is it, you won't find them again
this.href = this.href.replace("sss", StartDate); // sss no longer exists after this
this.href = this.href.replace("eee", EndDate); // sss no longer exists after this
What you will need to do is store the original href value before you modify it and then reference that when you want to update the link
$("#btnDateWiseGuestSearch").bind('click', function () {
var $this = $(this);
var originalhref = $this.data("href");
if(!originalhref){
this.data("href", this.href);
}
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
this.href = originalhref.replace("sss", StartDate).replace("eee", EndDate);
});

jQuery Validation Form span not working

I am using a online blog form validation which is done in jQuery, The problem I have with this file is when I reuse the input code for a different id, the span alert is not showing up.
$(document).ready(function() {
<!-- Real-time Validation -->
<!--Name can't be blank-->
$('#contact_name').on('input', function() {
var input=$(this);
var is_name=input.val();
if(is_name){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
$('#contact_nameee').on('input', function() {
var input=$(this);
var is_named=input.val();
if(is_named){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!--Email must be an email -->
$('#contact_email').on('input', function() {
var input=$(this);
var re = /^[a-zA-Z0-9.!#$%&'*+=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email=re.test(input.val());
if(is_email){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!--Website must be a website -->
$('#contact_website').on('input', function() {
var input=$(this);
if (input.val().substring(0,4)=='www.'){input.val('http://www.'+input.val().substring(4));}
var re = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/;
var is_url=re.test(input.val());
if(is_url){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!--Message can't be blank -->
$('#contact_message').keyup(function(event) {
var input=$(this);
var message=$(this).val();
console.log(message);
if(message){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!-- After Form Submitted Validation-->
$("#contact_submit button").click(function(event){
var form_data=$("#contact").serializeArray();
var error_free=true;
for (var input in form_data){
var element=$("#contact_"+form_data[input]['name']);
var valid=element.hasClass("valid");
var error_element=$("span", element.parent());
if (!valid){
error_element.removeClass("error").addClass("error_show");
error_free=false;
}
else{error_element.removeClass("error_show").addClass("error");}
}
if (!error_free){
event.preventDefault();
}
else{
alert('No errors: Form will be submitted');
}
});
});
I have done the jsFiddle .
Please look into it and help me out.
Thank you
The problem is the name of that element, you have added contact_ prefix to the name, remove it and it should be fine
<input type="text" id="contact_nameee" name="nameee"></input>
Demo: Fiddle

Categories

Resources