I have an MVC (Razor) web app. The form has 2 fields, one dropdown box (Kendo) and one input field for a date.
After the user makes a change on the dropdown, my 2nd input field is enabled or disabled based on the chosen type in the dropdown box. When the input field is disabled I fill the input with a default value.
When the user submits the form, I only get 2nd form field value posted in the viewmodel when the 2nd field is enabled, when disabled the value is not posted. I know this a common pattern in HTML, that disabled fields are not part of the POST.
My question: how can I solve this issue to get the value POSTed when the field is disabled ? It should be done in JS...
I had a similar requirement, what i did was, created a class , which would make the text box appear like disabled, by removing mouse events and styling a bit
[https://codepen.io/DawsonMediaD/pen/Dqrck][1]
or
Bit tricky, just before the post , enable all of them
Fixed it, in the onchange handler of the dropdown box attach this JS code:
var defaultDateValue = "2017-01-04"; //just for demo
var $effectiveToInput = $("##Html.IdFor(m => m.EffectiveToDate)");
$effectiveToInput.parent().append("<input type=\"hidden\" name=\"#Html.NameFor(m => m.EffectiveToDate)\" id=\"#Html.NameFor(m => m.EffectiveToDate)\" value=\"" + defaultDateValue +"\" />");
And for the other types, i clear the hidden fields with checks:
function removeHiddenEffectiveToDateField() {
var $effectiveToInput = $("##(Html.IdFor(m => m.EffectiveToDate))[type = hidden]");
if (null !== $effectiveToInput) {
$effectiveToInput.remove();
}
}
Related
I'm trying to programatically autofill my information on a form like this (Stripe's testing form) however I'm having trouble filling/selecting some of the fields.
For example, merely changing the Node's value attribute is not working for fields like the cardNumber field, and changing the selectedIndex attribute for the country does not have any effect.
Example:
selectedIndex = 40 from another index like 3 gives you Canada, which when done manually, will cause a Postal Code field to appear. However, I'm having trouble achieving this programmatically by just changing theselectedIndex
You can manually dispatch an event:
var select = document.getElementById('billingCountry')
select.dispatchEvent(new Event('change', { 'bubbles': true }))
Working on a small personal project with jQuery and JavaScript. This is a one page app on a static website.
The game (if you can call it that) asks the user to select 2 characters from the selection area and pressing enter transfers the input to the "battle-area" where when you hit the "fight" button random numbers are subtracted form the characters hitpoints as attack dmg.
I am stuck on the selection part. I need two separate input fields populated with unique names. I am able to write text into the field and transfer it but I want the input fields to be populated by clicking on the individual pictures on the screen. My code seems to populate both fields at once. I can hardcode two buttons to each populate one input field, the problem is that I have about 15 image buttons and I need to be able to click either of those to populate the fields.
function selectFighter(name) {
var x = name;
var input = $('#fighter1_name').val();
$('#fighter1_name').val(x);
if ($('#fighter1_name').val() != "") {
$('#fighter2_name').val(x);
}
}
I have tried to add a condition that checks the first input field for a value and if it is NOT empty, to instead write the input into the second field. But that is causing one button click to populate both fields. I need one button click to populate one field, and then when I click another button to populate the other, empty field.
I am passing in a name with an onclick event: onclick="selectFighter('bob');"
Problem is when I click the image, both fields are populated with the same name. I want to be able to click an image to populate one input field, and then click a different image and put that name in the input field.
This should do the trick. We're checking if the first field has a value - if so, we populate the second one - otherwise the first one.
function selectFighter(name) {
if ($('#fighter1_name').val()) {
$('#fighter2_name').val(name);
} else {
$('#fighter1_name').val(name);
}
}
Add a class to the elements you click, and an ID, and remove all inline javascript.
Then add a script tag with the event handler targeting the elements
$('.toBeClicked').on('click', function() {
var x = $(this).data('name'); // note that "name" is not a good name for a variable
var f1 = $('#fighter1_name');
var f2 = $('#fighter2_name');
f1.val() === "" ? f1.val(x) : f2.val(x);
});
$('#clear').on('click', function() { $('input[id^=fighter]').val("") })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="toBeClicked" data-name="bob">Bob</button>
<button class="toBeClicked" data-name="jon">Jon</button>
<button class="toBeClicked" data-name="ann">Ann</button>
<br><br>
Fighter 1 <input id="fighter1_name"><br>
Fighter 2 <input id="fighter2_name">
<br><br>
<button id="clear">Clear</button>
I have a text field that should be filled before custom saving through HTML custom button.
When a user fills this field and tries to save through custom button, the text inside this field is null even if the user fills it.
Any suggestions Please?
Many Thanks for replying to my query. Actually, I am calling the below function from custom HTML button and I saw the result from alert message as NULL value until I leave the text box. Once I click some other Field then I am getting right value and saving the record successfully. I have posted my code below please have a look and suggest me how I can achieve it. So how to get the text value if a user doesn't leave the text box and click on the Save button?
function createRecord() {
var oDescription = Xrm.Page.getAttribute("new_description").getValue();
if (oDescription != null) {
var callentity = {};
var activityId;
var currentUserId = Xrm.Page.context.getUserId();
var oLeadId = Xrm.Page.getAttribute("new_lead").getValue()[0].id;
callentity.Subject = "Call Activity";
callentity.Description = oDescription ;
XrmSvcToolkit.createRecord({....Some more functions here...
})
}
HTML Button code for calling above function
<input id="SaveCall" onclick="parent.createRecord()" type="button" value="Save Phonecall"></p>
Xrm.Page.getAttribute(arg).getValue(val) won't return a value until focus is lost from the arg attribute (as you've found out).
Some options you could try:
document.getElementById('new_description_i')[0].value
Removing focus from "new_description" on click of your button.
In my view model I have a field. This field can be selected from a drop down list or entered in a textbox. I have two radio buttons which allows to select between drop and textbox.
<div class="frm_row" id="contractorRow">
#Html.RadioButton("IsContractorNew", "false", true)
#Html.Label(#Resources.SomeLabels.Existing)
#Html.RadioButton("IsContractorNew", "true", false)
#Html.Label(#Resources.SomeLabels.New)
<div class="frm_row_input" id="contractorDropDownList">
#Html.DropDownListFor(model => model.CONTRACTOR, Model.Contractors)
#Html.ValidationMessageFor(model => model.CONTRACTOR)
</div>
<div class="frm_row_input" id="contractorTextBox" style="display: none;">
#Html.TextBoxFor(model => model.CONTRACTOR)
#Html.ValidationMessageFor(model => model.CONTRACTOR)
</div>
</div>
I prepared a javascript code for hiding, showing and clearing controls while selecting radio buttons. The problem is - field is bound only to the first control (drop down list).
EDIT:
I solved this problem by creating one hidden field and scripting whole logic to bind active control with it and therefore with the model. Anyway if anyone knows simpler solution, please post it.
I know this is an old question, but for those dealing with this issue, here's a solution:
Explanation
When a form is submitted, input elements are bound to the model by their name attribute. Let's say you use HTML helpers to generate your form, and you generate two input fields which bind to the same property on the model. When rendered to the DOM, they both have the same name attribute.
<input name="Passport.BirthPlace" id="birthPlaceDropDown" ... >
<input name="Passport.BirthPlace" id="birthPlaceInfoTextbox" ... >
When the form is submitted, it will bind the first (in the DOM) input it finds to Passport.BirthPlace
A Solution
The quick and easy way to fix this is to use JQuery to change the name of the field you don't want bound on submit. For me, I use a checkbox to toggle which field shows. When the checkbox changes, I hide one control, change its name attribute, and show the other one (and change it's name attribute to Passport.BirthPlace) It looks like this, basically:
First, I run this on document ready
$('#birthPlaceInfoTextbox').attr('name', 'nosubmit'); // Change name to avoid binding on inactive element
Then, I create a listener for my checkbox which toggles which control should be bound:
$('#notBornUSCheckbox').change(function() {
if (this.checked) {
// Not born us was checked, hide state dropdown and show freeform text box
$('#stateDropDownSection').addClass('d-none'); // Hide drop down
$('#birthPlaceDropDown').attr('name', 'nosubmit'); // Change name to something other than Passport.BirthPlace
$('#birthPlaceInfoTextbox').attr('name', 'Passport.BirthPlace'); // Set this one to be bound to the model
$('#stateTextboxSection').removeClass('d-none'); // Show the textbox field
} else { // Opposite of above lines
$('#stateDropDownSection').removeClass('d-none');
$('#stateTextboxSection').addClass('d-none');
$('#birthPlaceInfoTextbox').attr('name', 'nosubmit');
$('#birthPlaceDropDown').attr('name', 'Passport.BirthPlace');
}
});
Instead of using Razor #Html.TextBoxFor... for your textbox, you could try using raw HTML e.g. <input />. Also, have your JavaScript code remove the other field from the DOM entirely when a radio button is clicked, before submitting the form.
Here's the function that checks if the form is complete.
So, what I'm trying to do:
If radio is not selected, throw a message.
If radio is "yes", but text is not entered, throw error.
If radio is "no" but text is entered, make the text empty.
If all is good, add stuff into `allResponses
The form was displayed 5 times, and input was as follows:
Yes a1
No
Yes a3
No
Yes
Now, this input should display an error since in 5th case, "yes" is selected but nothing is entered in the textbox.
However, I get this:
http://i.imgur.com/ya2CUp0.png
Also, the text is not being updated as in 1st and 3rd cases.
I don't know a lot about JS, so please provide me with as explained responses as you can.
EDIT: Complete code: http://pastebin.com/scNSNM2H
Thanks
You have this in a loop:
var exaggerationPart = document.getElementById('exaggeration').value
And then you check to make sure it has a value for each item. But you will get the same value each time.
You are creating multiple inputs with the same id, "exaggeration". This is invalid HTML. Id's must be unique. To correct this, you can increment the id the same as you are doing with other elements (such as, input[name='response"+thisJokeIndex+"']).
var exaggerationPart = document.getElementById('exaggeration' + thisJokeIndex).value
tipTD2.append("<input type='text' name='exaggeration' id='exaggeration" + tipIndex + "' size='70'>")
Working demo: jsfiddle.net/svvge/2
Edit: To clear the value of the text box, you must change the value property of the text box element. Right now you are just changing the value of a variable.
var exaggerationInput = document.getElementById('exaggeration' + thisJokeIndex).value;
var exaggerationPart = exaggerationInput.value;
exaggerationInput.value = '';