Pass input text value to javascript not working - javascript

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
{ }

Related

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 :)

Javascript save , erase and reload input value

I have a problem with my Script. I want to do the following steps in this order:
1. Save the text in the input field.
2. Delete all text in the input field.
3. Reload the same text that was deleted before in the input field.
The problem with my script is that the ug()- function writes undefined in my textbox instead of the string that should be stored in var exput. The alert(exput) however shows me the correct content.
Help would be very much appreciated. And I'm sure there is better ways to do that, I'm quite new to this stuff.
HTML
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();deleter();ug()" />
Javascript
function merker() {
var merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
Your code is calling merker(); deleter(); ug(); in the onclick event, but ug() is already called by merker(). You should be doing this instead:
function merker() {
var merkzeug = document.getElementById('a').value;
deleter();
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();" />
I changed Your Javascript:
function merker() {
merkzeug = document.getElementById('a').value;//global variable without var
ug();//why You use it here? I think only for test. So delete it after.
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug() {
alert(merkzeug);
document.getElementById('a').value =merkzeug;
};
Problems with your code:
method ug was used with argument and without argument ( i changed to without )
to restore deleted value it must be saved to some variable, i saved to global merkzeug variable - this is not good practice but sufficient in this case
next i used merkzeug to restore value in textarea in ug() function
i do not know why You using ug() two times? maybe delete one of them is good thing to do.
In plunker - https://plnkr.co/edit/fc6iJBL80KcNSpaBd0s9?p=info
problem is: you pass undefined variable in the last ug function:
you do: merker(value) -> ug(value); delete(); ug(/*nothing*/);
or you set your merkzeung variable global or it will never be re-inserted in your imput:
var merkzeug = null;
function merker() {
merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
if (typeof exput === 'undefined') exput = merkzeung;
alert(exput);
document.getElementById('a').value = exput;
};

JavaScript checkbox Tree - children automatic checked

folks!
I've a litte problem, this is the situation:
Tree View
I let the tree on basis of the "lvl" create. That means, Bereich ABC is lvl1, Test1.docx is lvl4 and so on. So it's a "fake" Tree. But i have just this lvl information for every object.
I have to check the checkbox if the parent is clicked. that means, if lvl3 is clicked (for example "Originale") the lvl4 and lvl5 have to be checked also.
Do you understand what i mean? I hope so. But i can't make it working. Do you have any ideas?
$('[class^=lvl]').click(function(){
var keepChecking = true;
var currentElement = $(this);
var clickedLevel = getLevel(currentElement);
var checkValue = currentElement.is(':checked');
while (keepChecking) {
currentElement.attr('checked' , checkValue);
// get next element
currentElement = getNextCheckbox(currentElement);
var currentLevel = getLevel(currentElement);
keepChecking = (currentLevel > clickedLevel);
}
});
function getNextCheckbox(checkbox) {
return checkbox.parent().parent().next().children(":first").children(":first");
}
function getLevel(checkbox) {
var currentClass = checkbox.attr('class');
var currentLvl = currentClass.substring(3, currentClass.length);
return parseInt(currentLvl);
}
<TD class="center">
<INPUT TYPE="checkbox" NAME="" class="lvl[LL_REPTAG=PFADLEVEL /] docCheck" VALUE="[LL_REPTAG=DataId /]">
</TD>
I changed your javascript code to this:
function getNextCheckbox(checkbox) {
return checkbox.parent().parent().next().children(":first").children(":first");
}
function getLevel(checkbox) {
var currentClass = checkbox.attr('class');
if (currentClass){
var currentLvl = currentClass.substring(3, currentClass.length);
return parseInt(currentLvl);
}else{
return false;
}
}
$('[class^=lvl]').click(function(){
var currentElement = $(this);
var clickedLevel = getLevel(currentElement);
var checkValue = currentElement.is(':checked');
nextElement = getNextCheckbox(currentElement);
while ( getLevel(nextElement)>clickedLevel) {
currentElement=nextElement;
currentElement.prop('checked' , checkValue);
nextElement = getNextCheckbox(currentElement);
}
});
You can also play with it here: https://jsfiddle.net/1r73vy7z/1/
Enjoy :)

Explanation of this JavaScript Code

I'm not too good on the whole JavaScript (I can do some basic validations) but this isn't my zone
I've got a piece of code below that I'm trying to understand what it does, I can read any code and understand a few parts, but this just stumped me.
Here:
function tm_search_click() {
if (document.getElementById('tm').value == 'Enter your trademark') {
document.getElementById('tm').style.backgroundColor = '#fcc';
return false;
} else {
window.location = '?tm=' + escape(document.getElementById('tm').value);
return true;
}
}
function qs(a) {
a = a.replace(/[[]/, "\[").replace(/[]]/, "\]");
var b = "[\?&]" + a + "=([^&#]*)";
var c = new RegExp(b);
var d = c.exec(window.location.href);
return d == null ? "" : decodeURIComponent(d[1]).replace(/+/g, " ")
}
if (qs("tm") != "") {
tm_trademark = document.getElementById("tm").value = unescape(qs("tm"));
tm_partner = "migu2008";
tm_frame_width = 630;
tm_frame_height = "auto";
tm_trademark_country_code = "GB";
tm_css_url = "http://remarqueble.com/api/theme/search_corporate.css";
document.getElementById("tmLoading").style.display = "block";
tm_on_search_result = function () {
document.getElementById("tmLoading").style.display = "none";
document.getElementById("tmLoaded").style.display = "block"
}
} else {
tm_search_method = "none"
}
That is all of it without the <script> tags.
Could I also edit this code so that it searches are made based on what option the user inputs?
I think it works like this (assuming that this is in tags inside html page)
Page loads.
The script checks if URL has 'tm' parameter. If it has, then it sets bunch of tm_.. parameters and callback function. I don't know how they are used.
User clicks something that triggers the tm_search_click
Script sets new URL for the page and browser starts loading that
Goto step 1.

Two scripts Javascript doesn't work together

I have two scripts in a file active_form.js
The first script hides a text entry when a radiobutton is checked and the second does the same thing when a value is selected in a list.
When there are alone, the both work but together my function GereControleRadio do nothing.
edit : the two scripts are called in the same form.
The code of my scripts :
function GereControleRadio(Controleur, LabelControle, Controle, Masquer) {
var objLabelControle = document.getElementById(LabelControle);
var objControle = document.getElementById(Controle);
if (Masquer=='1') {
objControle.style.visibility=(objControleur.checked==true)?'visible':'hidden';
objLabelControle.style.visibility=(objControleur.checked==true)?'visible':'hidden';
}
else {
objControle.disabled=(objControleur.checked==true)?false:true;
objLabelControle.disabled=(objControleur.checked==true)?false:true;
}
return true;
};
function GereControleList(LabelControle, Controle, val) {
var objLabelControle = document.getElementById(LabelControle);
var objControle = document.getElementById(Controle);
if (val != '1% Patronal') {
objControle.style.visibility='hidden';
objLabelControle.style.visibility='hidden';
}
else {
objControle.style.visibility='visible';
objLabelControle.style.visibility='visible';
}
return true;
};
The .js is called in my view.yml
And I call the functions :
echo $form['etage']->render(array("onCLick" => "GereControleRadio('logement_etage_Etage', 'numetage_label', 'numetage_form, '1');"))
echo $form['reservataire']->render(array("onChange" => "GereControleList('patronal', 'patronal_form', 'this.value');"))
I believe you just have 2 functions with conflicting global scope variable names. Try replacing "GereControleList" with this...
function GereControleList(LabelControle, Controle, val) {
var objLabelControle_ = document.getElementById(LabelControle);
var objControle_ = document.getElementById(Controle);
if (val != '1% Patronal') {
objControle_.style.visibility='hidden';
objLabelControle_.style.visibility='hidden';
}
else {
objControle_.style.visibility='visible';
objLabelControle_.style.visibility='visible';
}
return true;
};
I have found the error : in GereControleRadio, I have deleted a line.
var objControleur = document.getElementById(Controleur);

Categories

Resources