JavaScript evaluates HiddenFor ONLY when stop to debug it (ASP MVC4) - javascript

I have a problem evaluating a hidden field in JavaScript (ASP MVC4)
I am using a model in my View and have a hidden input for a property in the model
#Html.HiddenFor(mdl => mdl.FilterByUser, new { #id = "filterByUserId" })
I have a Helper with a SearchBox, and on enter key pressed I am making the search.
$("#search-box").keydown(function (event) {
var keypressed = event.keyCode || event.which;
if (keypressed == 13) {
var searchValue = $("#search-box").val();
var filterByUser = $("#filterByUserId").val();
debugger;
window.location = "?searchValue=" + searchValue + "&filterByUser=" + filterByUser;
}
});
The problem is that var filterByUser has a value ONLY if I switch on the DeveloperTools and the browser stops in the "debugger".
If the tools are closed, I get "The parameters dictionary contains a null entry for parameter 'filterByUser' of non-nullable type 'System.Boolean' for method "
The other value, searchValue has no problem in being evaluated.
What can I do to fix this?
Thank you, Daniel

I got it. The problem was that the helper was already in a form. If I put a breakpoint/alert in the js keydown handler, it was executed. If not, the controller action was called using form.submit on textarea enter pressed.
My solve: the js handler was removed, and properties in form were adjusted to match the controller action properties.

Related

Angular JS form running only first time

I am at the very beginning with my Angular learning and I implemented this form:
http://codepen.io/jgrecule/pen/WxgqqO
What it is supposed to do is very basic: it consumes Flickr public JSONP feed as per Flicker specs https://www.flickr.com/services/feeds/docs/photos_public/ and renders the retrieved pictures thumbnails
The form I implemented has a submit button as well as a reset one. My problems I am trying too find solutions in the order of their importance are:
The very first time when you typing tags everything works but when u try to submit the request again by either adding a new tag or an user Id or anything it no longer works. I can see this warning in the logs but I have no idea what is causing it WARNING: Tried to load angular more than once.
The reset only works for the thumbnails but not for the other controls in my page
I would like to find a way to show an error message when the user pushes on the search flicker button and both tags and user ids input fields are empty. I tried to implement a custom directive but it was no way to get it working.
Thank you in advance for your inputs.
You are loading Angular more than once.
Your resetForm function doesn't reset the form at all. It just calls $setValidity on two of the form elements. It looks like it does try and reset the form in another part of your code with
document.getElementById("searchCriteriaTags").innerHTML = "";
document.getElementById("searchCriteriaIds").innerHTML = "";
document.getElementById("images").innerHTML = "";
which means you are modifying the DOM directly, about which see point 4.
You can add a simple check as to whether $scope.form.tags === '' and so the same for the other fields in your form.
Having addressed your 3 points, I'm afraid to say your code has bigger problems. You are modifying the DOM directly all over the place and you have a lot of duplicate code, plus lots of very complex conditionals.
EDIT 1 in response to OP's comment:
The Angular way of clearing form fields would be to simply clear the scope objects that the form fields are bound to. In other words it is as simple as doing something like:
$scope.tags = [] // for arrays
$scope.name = '' // for strings
Because the form fields are bound to these scope variables through the ng-model directive, changing the variables will also change the form fields.
Setting an error message when two fields are empty you can do like this:
$scope.checkFields = function(field1, field2) {
var oneEmpty = field1 === '';
var twoEmpty = field2 === '';
if (oneEmpty && twoEmpty) {
// call the failure message here
}
}
EDIT 2 in response comments:
Firstly good to see that your code is looking a lot cleaner. Secondly, the reason it fails is because in your search function you set the search fields to null, eg searchCriteria.tags = null;. You should set them to empty strings instead: searchCriteria.tags = '';.
I don't know what the purpose of checkFields is so I don't know where you want to place it. If you want to show an error message if the fields are empty then I'd say have checkFields() return a boolean and use ng-show to display the error div if checkFields() === false.
HTML:
<div ng-show="checkFields() === false">Fields can't be empty</div>
JS:
$scope.checkFields = function(field1, field2) {
var oneEmpty = field1 === '';
var twoEmpty = field2 === '';
return (oneEmpty || twoEmpty);
}

Search in mysql by Javascript

Good morning , I'm trying to do a check if the cpf entered already exists in the database , I'm using laravel , someone could help me in this function please ?
In my controller I seek and I list all cpfs in bank :
$cpfduplicado = UsuarioEsic::lists('doc', 'id')->all();
foreach ($cpfduplicado as $cpf)
if ($cpf == $request->cpf)
$cpf = 'verdadeiro';
// return redirect('/Esic/CadastroFisica');
return redirect('/Esic/Sucesso');
I'm not sure how to make a function in javascript to get this data and set a custom browser validity , I did something like this:
$(function cpfdupli(input) {
$('.btnCadastroo').on('click', function (json){
if (json.cpf === 'verdadeiro'){
document.getElementById('cpff');
input.setCustomValidity('Cpf já existe.');
} else {
input.setCustomValidity('');
}
});
});
I am beginner in the field and do not really know how to do this work, I just wanted the cpf existed already setasse one CustomValidity in the browser and not let him continue with the registration , if anyone can help me or give me other ways of how solve this I would be very grateful!
PS: Any questions about the code will be available to provide.
ok i will attempt to try and do what your looking for:
Say the html input is something like:
<input type="text" value="" id="cpff" />
Then we have some js to get the details within the above input box, the below does this on each lette typed into the input so its constantly checking as the user types then giving a visual reposnse as the user types so they now if its taken or not as typing:
$('input#cpff').on('keyup', function(evt){
//-- get for value on keyup
var inputValue = this.value;
//-- call to the controller to check
$.ajax({
url : '/check/cpff/',
type: 'POST',
data {cpffValue : inputValue},
success : function(res){
console.log(res);
if(res === 'succcess'){
//-- output a tick icon to let the user know all is ok so far
} else {
//-- output an red x to sai no its been used
}
},
error : function(msg, x){
console.log(msg);
}
})
});
So for each letter typed in the input box the code sends the value to the route /check/cpff and then this returns a boolean / string back to see if its ok or not, hopefully your still with me?
Route:
Route::post('/check/cpff', ['uses' => 'ControllerName#checkCPFF']);
Controller
Class ControllerName extends Controller {
public function checkCPFF(Request $request){
//-- get the ajax data variable -- cpffValue
$formValue = $request->get('cpffValue');
//-- lets chec to see if we have an entry with those values
$doesItExsist = ModelName::where('field_name',$formValue);
//-- if we have a result from the DB then return not allowed
return ($doesItExsist) ? 'not-allowed' : 'allowed'
}
}
SO the above controller takes the data value that the form submits, then checks the required db table and does a search for that value, if it cannot then the user has a valid entry if there is a value found then the user must change their entry etc
its a bit crude and i have nothing to test this with etc so might / will need better working / writing to work as such, you can always change the js to do the same on submitting the form instead etc,
here is a link to test out the input section. to veiw the result open the console up so you can see the values being typed. Example of keyup
i hope it gives your a sort of starting base for help...

ServiceNow show button if condition is true

I am trying to build a Client Script in ServiceNow - Geneva (function onChange), that does the following:
-> If the user writes something in an empty field a button should appear after change;
This is my code now, it doesn't work -> gives me an X on the form :):
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
//Define the variable and the name of the button
if (g_form.getValue('work_around') != ''){
var items = $$('BUTTON').each(function(item){
if(item.innerHTML.indexOf('Publish Known Error')=== -1){
item.show();
}
});
}
}
Instead of a Client Script, I would recommend using an onChange(<your field>) UI Policy. This can be accomplished by setting a Condition of your field not being NULL or some other value check.
Your UI Policy can then use the .append function to bind your button to an element of your choice.

Business required lookup set by javascript error

I´m working on a javascript event in dynamics crm 2013.
I have an option set (let´s call it fieldA). When it changes, I want to set the value of a lookup (let´s call it fieldB). This lookup is mandatory (or business required as CRM calls it).
Here is my code:
function fieldAOnChange() {
/* computation of field B value: entityId, name, entityType */
var lookupField = Xrm.Page.getAttribute(fieldBId);
if (!isUndefined(lookupField)) {
if (entityId != null && name != null && entityType != null) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = entityId;
lookupValue[0].name = name;
lookupValue[0].entityType = entityType;
lookupField.setValue(lookupValue);
} else {
lookupField.setValue(null);
}
lookupField.fireOnChange();
}
}
This code works almost fine. The lookup is correctly filled, however the icon "this is a mandatory field and it´s not filled" appears next to the field. This is what I´m trying to fix !
If I click on the field to get the focus and then elsewhere to lose it, the icon disappear. If I change again the value in the option set and the fieldB is updated again, the icon disappear also.
I have tried stupid things like setting the focus on and off or launching the fireOnChange event twice without results.
Am I doing something wrong ?

How can I make this username suggestion work in javascript?

I have an application that requires both first name and last name. I need to have the username field automatically fill up as the user types in their first and last names to suggest a username. Right now, it works to a degree. This is the function that executes on a keyup for the name fields.
suggestUsername: function() {
var username = this.$('#user_login_field').val();
var first = this.$('#user_first_name_field').val();
var last = this.$('#user_last_name_field').val();
if(first == '' && last == ''){
this.$('#user_login_field').val('');
} else {
this.$('#user_login_field').val(first+'.'+last);
}
},
This works unless the user adds something to the username manually and then goes back to one of the name fields and enters something else. In the case that that happens, whatever the user added manually disappears. Not sure how to go about fixing it
Add an jQuery focus handler to the #user_login_field that unbinds the keypress events from the first and last name fields. (http://api.jquery.com/focus/)
$('#user_login_field').focus(function (e) {
// Unbind the keyup events
$('#user_first_name_field').unbind('keypress');
$('#user_last_name_field').unbind('keypress');
});
you can add a
$('#user_last_name_field').blur(function(){
//do username suggestion
})

Categories

Resources